Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify which MP3 file ended in MediaPlayer.OnCompletionListener?

In my ativity's onCreate(), I set a MediaPlayer.OnCompletionListener, then play an MP3 file:

    MediaPlayer p = MediaPlayer.create(this, R.raw.intro);
    p.setOnCompletionListener(this);
    p.start();      

And when playing ends, I just handle this event in:

    public void onCompletion(MediaPlayer mp) {
      // handle completion
    }

All nice and dandy but now I want to play two different MP3 files and handle completion differently based on which file was played.

Is there a way to tell from the MediaPlayer parameter which piece ended?

like image 351
ateiob Avatar asked Mar 01 '12 00:03

ateiob


People also ask

Which MediaPlayer callback method will notify us when the MediaPlayer has finished playing the audio file?

OnCompletionListener. Interface definition for a callback to be invoked when playback of a media source has completed.

What is MediaPlayer class?

android.media.MediaPlayer. MediaPlayer class can be used to control playback of audio/video files and streams. MediaPlayer is not thread-safe. Creation of and all access to player instances should be on the same thread. If registering callbacks, the thread must have a Looper.

What is Android Media player?

Advertisements. Android provides many ways to control playback of audio/video files and streams. One of this way is through a class called MediaPlayer.


2 Answers

The callback public void onCompletion(MediaPlayer mp) gives you a reference to the MediaPlayer.

public void onCompletion(MediaPlayer mp) {
    if (mp.equals(p){
        //do action for media player p

    } else if (mp.equals(q)){
        //do action for media player q
    }
}
like image 159
edthethird Avatar answered Oct 20 '22 22:10

edthethird


The OnSetCompletionListener triggered identifies which MediaPlayer completed. As to the mp3 file, your data model should be expressed as a list of MediaPlayer objects (objects may be create from subclass of MediaPlayer) which should know the mp3 file they are playing or completed playing. See http://davanum.wordpress.com/2007/12/29/android-videomusic-player-sample-from-local-disk-as-well-as-remote-urls/ for example As to the model create a class that inherits from MediaPlayer. In that new class maintain the mp3 file name - like 'fn'. So then p.fn gives you the file for the mp3

like image 35
mozillanerd Avatar answered Oct 20 '22 23:10

mozillanerd