现在我想出了一个非常简单的 AudioPool 类,它可以播放随后使用 MediaPlayer 类添加到其中的音频。这个实现肯定还不成熟,但我只是想分享它,因为它至少给出了一些如何轻松实现它的想法。如果您发现本课程有任何问题,请告诉我们。
用法:
AudioPool ap = new AudioPool();
File root = Environment.getExternalStorageDirectory() ;
int id1 = ap.addAudio(root + "/gong1.mp3");
int id2 = ap.addAudio(root + "/gong2.mp3");
int id3 = ap.addAudio(root + "/gong3.mp3");
ap.playAudio(id1);
ap.playAudio(id3);
ap.playAudio(id3);
ap.playAudio(id2);
随后将播放 gong1 -> gong3 -> gong3 -> gong1。因为这基本上是我需要的,所以我把它留在这里......
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.util.Log;
public class AudioPool {
static String TAG = "AudioPool";
MediaPlayer mPlayer;
int mAudioCounter;
int mCurrentId;
HashMap<Integer, String> mAudioMap;
LinkedList<Integer> mAudioQueue;
public AudioPool() {
mAudioMap = new HashMap<Integer, String>();
mAudioQueue = new LinkedList<Integer>();
mAudioCounter = 0;
}
public int addAudio(String path) {
Log.d(TAG, "adding audio " + path + " to the pool");
if (mAudioMap.containsValue(path)) {
return getAudioKey(path);
}
mAudioCounter++;
mAudioMap.put(mAudioCounter, path);
return mAudioCounter;
}
public boolean playAudio(int id) {
if (mAudioMap.containsKey(id) == false) {
return false;
}
if (mPlayer == null) {
setupPlayer();
}
if (mPlayer.isPlaying() == false) {
return prepareAndPlayAudioNow(id);
} else {
Log.d(TAG, "adding audio " + id + " to the audio queue");
mAudioQueue.add(id);
}
return true;
}
public Integer[] getAudioIds() {
return (Integer[]) mAudioMap.keySet().toArray(
new Integer[mAudioMap.keySet().size()]);
}
public void releaseAudioPlayer() {
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
private boolean prepareAndPlayAudioNow(int id) {
mCurrentId = id;
try {
Log.d(TAG, "playing audio " + id + " now");
mPlayer.reset();
mPlayer.setDataSource(mAudioMap.get(id));
mPlayer.prepare();
mPlayer.start();
return true;
} catch (Exception e) {
Log.d(TAG, "problems playing audio " + e.getMessage());
return false;
}
}
private boolean playAudioAgainNow() {
try {
mPlayer.seekTo(0);
mPlayer.start();
return true;
} catch (Exception e) {
Log.d(TAG, "problems playing audio");
return false;
}
}
private void setupPlayer() {
mPlayer = new MediaPlayer();
mPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
audioDone();
}
});
}
private void audioDone() {
if (mAudioQueue.size() > 0) {
Log.d(TAG, mAudioQueue.size() + " audios in queue");
int nextId = mAudioQueue.removeFirst();
if (mCurrentId == nextId) {
playAudioAgainNow();
} else {
prepareAndPlayAudioNow(nextId);
}
} else {
releaseAudioPlayer();
}
}
private int getAudioKey(String path) {
for (Map.Entry<Integer, String> map : mAudioMap.entrySet()) {
if (map.getValue().compareTo(path) == 0) {
return map.getKey();
}
}
return -1;
}
}