我正在 LibGDX 中制作一个游戏,我需要同时播放 2 个旋律。但是在Android上加载和播放2旋律不起作用。这是我做的一个小测试。我甚至尝试使用LibGDX资产管理器,但仍然没有成功。
Music test1;
Music test2;
AssetManager manager = new AssetManager();
@Override public void create()
{
manager.load(Melody.REVERSION.getPath(), Music.class);
manager.load(Melody.COLLAPSE.getPath(), Music.class);
while (!manager.update()) {}
manager.finishLoading();
test1 = manager.get(Melody.REVERSION.getPath());
test2 = manager.get(Melody.COLLAPSE.getPath());
test1.setVolume(1);
test1.play();
test2.setVolume(1);
test2.play();
}
我目前正在使用SoundPool库。有了这个,我可以同时再现不同的声音效果,但我不知道这是不是音乐的最佳方法。
帖子相关:使用soundpool示例播放声音
使用MediaPlayer和CyclicBarrier进行编辑:
public enum MP_COMMAND {
START,
STOP,
PAUSE
}
/**
* Uses threads to execute synced commands for the current video media player and
* background music player in tandem.
*/
public void syncedCommand(MediaPlayer player1, MediaPlayer player2, MP_COMMAND command) {
final CyclicBarrier commandBarrier = new CyclicBarrier(2);
new Thread(new SyncedCommandService(commandBarrier, player1, command)).start();
new Thread(new SyncedCommandService(commandBarrier, player2, command)).start();
}
/**
* Inner class that starts a given media player synchronously
* with other threads utilizing SyncedStartService
*/
private class SyncedCommandService implements Runnable {
private final CyclicBarrier mCommandBarrier;
private MediaPlayerTest.MP_COMMAND mCommand;
private MediaPlayer mMediaPlayer;
public SyncedCommandService(CyclicBarrier barrier, MediaPlayer player, MediaPlayerTest.MP_COMMAND command) {
mCommandBarrier = barrier;
mMediaPlayer = player;
mCommand = command;
}
@Override public void run() {
try {
mCommandBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
switch (mCommand) {
case START:
mMediaPlayer.start();
break;
case STOP:
mMediaPlayer.stop();
break;
case PAUSE:
mMediaPlayer.pause();
break;
default:
break;
}
}
}
要播放这两首歌,请调用以下命令:
MediaPlayer mCurrentVideoPlayer = MediaPlayer.create(this, R.raw.track1);
MediaPlayer mBackgroundMusic = MediaPlayer.create(this, R.raw.track2);
syncedCommand(mCurrentVideoPlayer, mBackgroundMusic, MP_COMMAND.START);
参考:用MediaPlayer同时播放多首歌曲:只有一首是真的在播放