我有8个mp3文件。而且我必须同时播放(几乎不会。肯定会)
我使用'AudaCity'来控制精度。但是我的代码没有给我想要的结果......
(异步= 30~90 ms)
所以,这是我的代码:
(首次开始玩)
public void start() {
//songInfo.getMediaPlayer() - it's array of MediaPlayers, source already setted
for (MediaPlayer player : songInfo.getMediaPlayer()) {
try {
if (player != null) {
player.prepare();
player.seekTo(0);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
songInfo.getMediaPlayer()[0]
.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
//code for play next setlist
}
});
resume();
}
(暂停)
public void pause() {
for (MediaPlayer player : songInfo.getMediaPlayer()) {
if (player != null)
player.pause();
}
}
(暂停后恢复,开始播放(第一种方法))
public void resume() {
int pos = songInfo.getMediaPlayer()[0].getCurrentPosition();
long iTime = System.currentTimeMillis();
for (MediaPlayer player : songInfo.getMediaPlayer()) {
if (player != null) {
player.seekTo(pos + (int)(System.currentTimeMillis()-iTime));
player.start();
}
}
}
如果我第一次开始玩,它会给我异步~30ms +
然后在暂停/恢复之后它会发挥完美。
答案 0 :(得分:5)
经过大量研究,问题得以解决。
要同时播放多个曲目,您应该使用AsyncTask并在THREAD_POOL_EXECUTOR上执行它
怎么做:
主题类:
class PlayThread extends AsyncTask<MediaPlayer, Void, Void>
{
@Override
protected Void doInBackground(MediaPlayer... player) {
player[0].start();
return null;
}
}
媒体播放器:
MediaPlayer[] players = new MediaPlayer[5];
//Then set source to each player...
//...
//Create objects of Thread class
PlayThread[] playThreads = new PlayThread[5];
for (int i = 0; i < 5; i++)
playThreads[i] = new PlayThread();
//Set Media Players there and start play
for (int i = 0; i < 5; i++)
playThreads[i].executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, players[i]);
AsyncTask只能同时执行5个线程,其他的将进入队列。
SoundPool缓冲区限制为1Mb,因此根本不是解决方案。
非常重要:
要同时播放更多音频曲目,您应该将它们混合到1个缓冲区中
执行此操作的方法:将mp3解码为pcm(以流模式转换为小缓冲区),将其混合到一个字节缓冲区中并将其放入AudioTrack进行播放。