Setting an array of songs using MediaPlayer

前端 未结 3 1196
离开以前
离开以前 2021-02-10 16:43

I have 5 songs which i need to play one after the other, and it must loop from the first song after finishing the 5th song. How do I use the MediaPlayer to achieve this?

3条回答
  •  走了就别回头了
    2021-02-10 17:03

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

提交回复
热议问题