使用MediaPlayer设置歌曲数组

时间:2011-09-12 04:40:44

标签: android android-mediaplayer

我有5首歌我需要一个接一个地播放,并且必须在完成第5首歌之后从第一首歌开始。 如何使用MediaPlayer实现此目的?

3 个答案:

答案 0 :(得分:11)

public class MediaPlayerExample extends Activity implements MediaPlayer.OnCompletionListener {
 int [] songs;
MediaPlayer mediaPlayer;
int current_index = 0; 
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

songs= new int[] {R.raw.song1,R.raw.song2,R.raw.song3,R.raw.song4};

mediaPlayer = MediaPlayer.create(this, songs[0]);

mediaPlayer.setOnCompletionListener(this);

mediaPlayer.start();

}
@Override
    public void onCompletion(MediaPlayer mp) {
        play();

    }

 private void play()
    {
        current_index = (current_index +1)% 4;
        AssetFileDescriptor afd = this.getResources().openRawResourceFd(songs[current_index]);

        try
        {   
            mediaPlayer.reset();
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
            mediaPlayer.prepare();
            mediaPlayer.start();
            afd.close();
        }
        catch (IllegalArgumentException e)
        {
            Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
        }
        catch (IllegalStateException e)
        {
            Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
        }
        catch (IOException e)
        {
            Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
        }
    }
}

答案 1 :(得分:0)

你需要使用CountDownTimer。 CountDown计时器让您可以逐个执行此操作::

MediaPlayer mp_xmPlayer2  = new MediaPlayer();
mp_xmPlayer2 = MediaPlayer.create(this, R.raw.bg_music_wav);   


 for(int i=0;i<5;i++)
    {
    CountDownTimer cntr_aCounter = new CountDownTimer(3000, 1000) {
        public void onTick(long millisUntilFinished) {

            mp_xmPlayer2.start();
        }

        public void onFinish() {
            //change music name
          }
        };
        cntr_aCounter.start();
    }

答案 2 :(得分:0)

简单:

testConnection