英文:
Android Studio Java MediaPlayer plays only the first second of audio and then stops
问题
我尝试让MediaPlayer播放大约两分钟长的mp3音频,但只播放了第一秒,然后播放器就停止了。我尝试过mp3和wav格式。以下是我的代码:
package com.pi.audiodemo;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mediaPlayer = (MediaPlayer) MediaPlayer.create(this, R.raw.dumb);
mediaPlayer.start();
}
}
英文:
I'm trying to have MediaPlayer play a roughly two minute long mp3 audio, however only the first second is played then the player stops. I've tired both mp3 and wav formats. Here's my code:
package com.pi.audiodemo;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mediaPlayer = (MediaPlayer) MediaPlayer.create(this, R.raw.dumb);
mediaPlayer.start();
}
}
</details>
# 答案1
**得分**: 1
你在`onCreate`函数内创建了`MediaPlayer`。因此,在函数返回后,它将被删除。尝试以下代码:
```Java
package com.pi.audiodemo;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = (MediaPlayer) MediaPlayer.create(this, R.raw.dumb);
mediaPlayer.start();
}
}
英文:
You create MediaPlayer
within the onCreate
function. So it will be deleted right after function returns. Try the following code:
package com.pi.audiodemo;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = (MediaPlayer) MediaPlayer.create(this, R.raw.dumb);
mediaPlayer.start();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论