2013-02-24 100 views
1

我使用startActivityForResult從列表視圖中獲取音樂文件的路徑,然後使用MediaPlayer.setDataSource(STRING);爲MediaPlayer設置該字符串第一次使用按鈕播放歌曲時,它會播放所有權限,如果在歌曲播放時單擊按鈕玩它會重置並再次播放。MediaPlayer只播放一次

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

但是,如果我點擊按鈕播放完成,它將不會再次播放。

startActivityForResult

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

在列表視圖:

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

回答

1

我認爲你需要mMediaPlayer.seekTo(0)爲了重播,因爲它已經完成。

See the android doc page


編輯:圖

尋找enter image description hereStarted之間< - >PlaybackCompleted似乎只有一個,以重新啓動播放器動作......你不需要prepare你有:(.. 。

我明白爲什麼你想prepare所以我建議OnCompletetionListenermMediaPlayer.stop()以移動到Stopped狀態d準備好下一個prepare()

+0

這隻會播放聲音的兩倍。 – 2013-02-24 17:21:37

+0

好多了!添加了其他建議! – madlymad 2013-02-24 17:34:09

+0

我剛剛添加了OnCompletionListener並添加了mMediaPlayer.stop(),仍然是相同的結果,在歌曲完成後它不能再次播放,直到我再次加載它 – 2013-02-24 17:40:42

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(); 
     } 
    }); 
} 

}