MediaPlayer只播放一次

时间:2013-02-24 17:08:06

标签: java android android-listview android-mediaplayer

我使用startActivityForResult从listview中获取音乐文件的路径,然后使用MediaPlayer.setDataSource(STRING);为MediaPlayer设置该字符串第一次使用按钮播放歌曲时,它播放正常,如果我在播放歌曲时单击按钮它将重置并再次播放。

  if (mMediaPlayer.isPlaying()) {
                  mMediaPlayer.reset();
         }

但是,如果点击按钮播放完成,它将无法再次播放。

startActivityForResult

Intent i = new Intent(MainActivity.this, Activityone.class);
                    startActivityForResult(i, 0);
                    mMediaPlayer.reset();

在Listview中:

 music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
String filename = musiccursor.getString(music_column_index);
Intent person = new Intent();
Bundle backpack = new Bundle();
backpack.putString("arnswer", filename);
person.putExtras(backpack);
setResult(RESULT_OK, person);
finish();

onActivityResult:

  if (resultCode == RESULT_OK){
               if(requestCode == 0) {
                // handling code of startActivityForResult of first button
               Bundle basket = data.getExtras();
                 s = basket.getString("arnswer");
    }

和按钮启动MediaPlayer:

public void pbutton1(View view) {
       try {
           if (mMediaPlayer.isPlaying()) {
                 mMediaPlayer.reset();
        }
         mMediaPlayer.setDataSource(s); //using string here
         mMediaPlayer.prepare();
        mMediaPlayer.start();
   } catch (Exception e) {

   }

LogCat:

enter image description here

2 个答案:

答案 0 :(得分:1)

我认为您需要mMediaPlayer.seekTo(0)才能重播,因为它已经完成了。

See the android doc page


编辑:

Started< - >之间查看图表enter image description here PlaybackCompleted似乎只是一个动作才能重新启动播放器......你不需要prepare你有:{...

我理解为什么你想要prepare ,所以我建议OnCompletetionListenermMediaPlayer.stop(),以便转移到Stopped状态并做好准备下一个prepare()

答案 1 :(得分:0)

此代码完美无缺。我希望能帮到你。

public class PianoActivity extends Activity {

private MediaPlayer mediaPlayer = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_piano);
    setupUI();
}

@Override
protected void onPause() {
    super.onPause();
    if (mediaPlayer != null) {
        mediaPlayer.release();
        mediaPlayer = null;
    }
}

private void setupUI() {
    findViewById(R.id.doo).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            managerOfSound();
        }
    });
}

private void managerOfSound() {
    mediaPlayer = MediaPlayer.create(this, R.raw.doo);
    if (!mediaPlayer.isPlaying()) {
        mediaPlayer.start();
    } else {
        mediaPlayer.stop();
    }
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            mp.reset();
            mp.release();
        }
    });
}

}