1

我在 MediaPlayer for android 中播放多个 mp3 文件时遇到问题...它将所有文件一起播放并造成混乱。我想要的解决方案是一次播放每个文件,然后播放其他文件。

4

3 回答 3

7

你可以尝试这样的事情:

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();
      }
    }
}
于 2013-01-27T15:16:03.830 回答
5

我通过以下代码做到了这一点:

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();
}
于 2013-11-02T16:13:10.690 回答
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)

于 2012-06-06T14:21:12.753 回答