如何循环播放Media Player文件?

时间:2012-08-14 11:35:38

标签: android loops media-player android-mediaplayer

基本上我有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();

        }
    });
}

1 个答案:

答案 0 :(得分:7)

调用该函数:

MediaPlayer.setLooping(true|false)

调用MediaPlayer.prepare()

后,在mediaplayerObject上

示例:

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