2012-08-14 91 views
4

基本上我有3首歌曲,我希望用戶能夠在3首歌曲的週期完成後循環回第一首歌曲。爲什麼這不工作?它將播放所有3首歌曲,然後在第四次點擊時,不播放任何歌曲。如何循環播放媒體播放器文件?

MediaPlayer song0, song1, song2; 
Button play, next; 
ArrayList<MediaPlayer> music = new ArrayList<MediaPlayer>(); 
int track = 0; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 


    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    song0 = MediaPlayer.create(TheParty0Activity.this, R.raw.blacksunempire); 
    song1 = MediaPlayer.create(TheParty0Activity.this, R.raw.blueskies); 
    song2= MediaPlayer.create(TheParty0Activity.this, R.raw.fuckingnoise); 

    music.add(song0); 
    music.add(song1); 
    music.add(song2); 

    play = (Button) findViewById(R.id.button0); 
    next = (Button) findViewById(R.id.button1); 

    play.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      music.get(track).start(); 

     } 
    }); 

    next.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      music.get(track).stop(); 
      track++; 
      if(track == 3) 
       track = 0; 

      music.get(track).start(); 

     } 
    }); 
} 
+0

你到底想要做/什麼。 .. ??? – SilentKiller 2012-08-14 11:41:15

+0

在重新啓動媒體播放器之前,您應該重新啓動媒體播放器 – 2012-08-14 11:43:40

回答

7

調用該函數:在mediaplayerObject

MediaPlayer.setLooping(true|false)

以後你就叫MediaPlayer.prepare()

例子:

Uri mediaUri = createUri(context, R.raw.media); // Audiofile in raw folder 
Mediaplayer mPlayer = new MediaPlayer(); 
mPlayer.setDataSource(context, mediaUri); 
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); 
mPlayer.prepare(); 

mPlayer.setLooping(true); 

mPlayer.start(); 
+2

請注意,無法設置有限數量的循環,並且(根據我的經驗)循環絕對不是無縫的。如果預加載聲音不成問題,那麼SoundPool在循環方面會更好。 – 2012-08-23 12:37:12

+0

@sebweisgerber它會播放多少聲音 – rup35h 2015-09-21 13:53:59

+0

無限期地調用http://developer.android.com/reference/android/media/MediaPlayer.html#stop() – 2015-09-21 14:13:25