在MediaPlayer中一个接一个地播放多个文件在android中

时间:2012-06-06 14:20:19

标签: android

我在MediaPlayer for android中播放多个mp3文件时遇到问题...它将所有文件一起播放并创建混乱。我希望解决方案是它一次只播放每个文件然后播放其他文件。

3 个答案:

答案 0 :(得分:6)

您可以尝试这样的事情:

public class MainActivity extends Activity implements MediaPlayer.OnCompletionListener
{
    int[] tracks = new int[3];
    int currentTrack = 0;
    private MediaPlayer mediaPlayer = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      tracks[0] = R.raw.say1;
      tracks[1] = R.raw.say2;
      tracks[2] = R.raw.say3;
      mediaPlayer = MediaPlayer.create(getApplicationContext(), tracks[currentTrack]);
      mediaPlayer.setOnCompletionListener(this);
      mediaPlayer.start();
    }

    public void onCompletion(MediaPlayer arg0) {
      arg0.release();
      if (currentTrack < tracks.length) {
        currentTrack++;
        arg0 = MediaPlayer.create(getApplicationContext(), tracks[currentTrack]);
        arg0.setOnCompletionListener(this);
        arg0.start();
      }
    }
}

答案 1 :(得分:3)

我是通过以下代码完成的:

private ArrayList<MediaPlayer> mPlayerList = new ArrayList<MediaPlayer>();
public void playSound4FileList(ArrayList<String> fileList) 
{
    mPlayerList.clear();
    for (String fileName : fileList)
    {
        try {
            MediaPlayer mPlayerT = new MediaPlayer();

            AssetFileDescriptor descriptor = context.getAssets().openFd(fileName);
            mPlayerT.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
            descriptor.close();

            mPlayerT.prepare();
            mPlayerT.setVolume(1f, 1f);
            mPlayerT.setLooping(false);

            mPlayerList.add(mPlayerT);

        } catch (Exception e) {
        }

    }
    for (int i=0; i<mPlayerList.size()-1; i++) //Do not include last element
    {
        mPlayerList.get(i).setNextMediaPlayer(mPlayerList.get(i+1));

    }

    mPlayerList.get(0).start();
}

答案 2 :(得分:2)

有各种MediaPlayer回调使用它们:

http://www.androidadb.com/class/on/OnCompletionListener.html

mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {

    public void onCompletion(MediaPlayer theMediaPlayer) {
        mParent.playNextAudio();
        mParent = null;
    }

http://developer.android.com/reference/android/media/MediaPlayer.html#setOnCompletionListener(android.media.MediaPlayer.OnCompletionListener)