3 回答

TA貢獻(xiàn)1911條經(jīng)驗 獲得超7個贊
在一個按鈕中:
Intent intent_upload = new Intent();
intent_upload.setType("audio/*");
intent_upload.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent_upload, 222);
結(jié)果:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 222:
if (requestCode == 222) {
if (resultCode == RESULT_OK) {
//the selected audio.
Uri uri = data.getData();
MediaPlayer mediaPlayer = MediaPlayer.create(this, uri);
mediaPlayer.setLooping(false);
mediaPlayer.setOnPreparedListener(mp -> mp.start());
mediaPlayer.setOnCompletionListener(mp -> finish());
}
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
我試過了,效果很好,也許您在活動中遺漏了什么?

TA貢獻(xiàn)1993條經(jīng)驗 獲得超6個贊
你應(yīng)該使用mp.pause()而不是finish()
mediaPlayer = MediaPlayer.create(MainActivity.this,
Uri.parse(audio.getaPath()));
mediaPlayer.setLooping(false);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
public void onPrepared(MediaPlayer mp)
{
mp.start();
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer mp)
{
mp.pause();
}
});

TA貢獻(xiàn)1890條經(jīng)驗 獲得超9個贊
試試這個代碼
private MediaPlayer mMediaPlayer;
public void stop() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
public void play(Context context, String name) {
stop();
//mMediaPlayer = MediaPlayer.create(c, rid);
mMediaPlayer = MediaPlayer.create(context, Uri.parse("android.resource://"+ context.getPackageName()+"/your_file/"+name+".mp3"));
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
stop();
}
});
添加回答
舉報