【发布时间】:2016-01-29 17:58:53
【问题描述】:
public class AndroidSound implements Sound {
int soundId;
SoundPool soundPool;
public AndroidSound(SoundPool soundPool, int soundId) {
this.soundId = soundId;
this.soundPool = soundPool;
}
@Override
public void play(float volume) {
soundPool.play(soundId, volume, volume, 0, 0, 1);
}
@Override
public void dispose() {
soundPool.unload(soundId);
}}
public class Assets{
public Music theme;
public static Sound sound;
public static void load(Game game) {
theme = game.getAudio().createMusic("theme.mp3");
theme.setLooping(true);
theme.setVolume(0.85f);
theme.play();
sound = game.getAudio().createSound("death.wav");
}
}
然后我通过调用 play() 在不同的类中播放这个声音,但它的播放延迟非常大,大约 500 毫秒。这是为什么?我试图寻找解决方案,但是有很多人遇到这个问题,我还没有找到任何真正有效的答案。大多数主题有点老了,也许已经有一个简单的解决方案了,指望你的帮助。
public class AndroidAudio implements Audio {
AssetManager assets;
SoundPool soundPool;
public AndroidAudio(Activity activity) {
activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
this.assets = activity.getAssets();
this.soundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
}
@Override
public Sound createSound(String filename) {
try {
AssetFileDescriptor assetDescriptor = assets.openFd(filename);
int soundId = soundPool.load(assetDescriptor, 0);
return new AndroidSound(soundPool, soundId);
} catch (IOException e) {
throw new RuntimeException("Couldn't load sound '" + filename + "'");
}
}
}
【问题讨论】:
-
你是如何创建
AndroidSound对象实例的? -
为什么会延迟播放?我已经对此感到非常沮丧,找不到任何好的解决方案。我应该使用 SoundPool 以外的东西吗?或者有没有可能是我的设备故障? (我没有其他选项可以检查)
-
所以你在
onLoadComplete(SoundPool soundPool, int sampleId, int status)方法中调用play并且在你调用play之后你注意到半秒延迟? -
我在完全不同的类中调用 play,当我启动应用程序时,这个 load(Game game) 方法在我的加载屏幕中被调用,所以在我调用它之前很久就分配了声音(比如这个 Assets .sound.play(0.85f))。没有 onLoadComplete 方法,只是在我检测角色何时死亡的方法中(因此是“death.wav”)。