如何在 Android 中加速 SoundPool?
How to speed up SoundPool in Android?
我正在尝试创建一个简单的摩尔斯电码应用程序。当用户按下按钮时,莫尔斯音应该在松开时开始,然后结束。
问题在于延迟 - 直到用户按下按钮大约 400 毫秒后莫尔斯音才会开始。我不确定为什么会这样,但在研究了这个问题之后,我认为这是我的代码的结构方式。我要播放的文件是 Mp3 格式,位于原始文件夹中。
我使用 Media Player 完成了这个,但我 运行 遇到了同样的问题,因为它没有足够的响应,所以我选择尝试使用声音池。有谁知道 advice/suggestions 我怎样才能加快操作速度?这对我来说是发展的新领域。
public int S1 = R.raw.morse;
private SoundPool soundPool;
private boolean loaded;
static int x;
public void initSounds(Context context) {
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
final int y = soundPool.load(context, R.raw.morse, 1);
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
playSound(y);
}
});
}
public void playSound(int soundID) {
if(loaded) {
x = soundPool.play(soundID, 0.5f, 0.5f, 1, 0, 1f);
}
}
//Calling code
pad.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
//State of a toggle button
if(audioOnOff==true) {
//Sound pool object is created and initialized as a global variabe
sp.initSounds(getApplicationContext());
}
}
在我看来这里发生的事情是每次按下按钮时,您都在加载声音,等待它完成加载,然后播放它。您真正想要的是加载一次声音 ,然后每次按下按钮时播放它。
因此,不要在 onTouchListener 中调用 initSounds,而是在按下按钮之前在其他地方调用 initSounds。然后在你的 onTouchListener 中调用你的 playSound 方法。
最后,确保从 onLoadCompleteListener 中删除 playSound 方法调用,这样您在最初加载声音时就不会听到神秘的噪音 ;)
我正在尝试创建一个简单的摩尔斯电码应用程序。当用户按下按钮时,莫尔斯音应该在松开时开始,然后结束。
问题在于延迟 - 直到用户按下按钮大约 400 毫秒后莫尔斯音才会开始。我不确定为什么会这样,但在研究了这个问题之后,我认为这是我的代码的结构方式。我要播放的文件是 Mp3 格式,位于原始文件夹中。
我使用 Media Player 完成了这个,但我 运行 遇到了同样的问题,因为它没有足够的响应,所以我选择尝试使用声音池。有谁知道 advice/suggestions 我怎样才能加快操作速度?这对我来说是发展的新领域。
public int S1 = R.raw.morse;
private SoundPool soundPool;
private boolean loaded;
static int x;
public void initSounds(Context context) {
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
final int y = soundPool.load(context, R.raw.morse, 1);
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
playSound(y);
}
});
}
public void playSound(int soundID) {
if(loaded) {
x = soundPool.play(soundID, 0.5f, 0.5f, 1, 0, 1f);
}
}
//Calling code
pad.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
//State of a toggle button
if(audioOnOff==true) {
//Sound pool object is created and initialized as a global variabe
sp.initSounds(getApplicationContext());
}
}
在我看来这里发生的事情是每次按下按钮时,您都在加载声音,等待它完成加载,然后播放它。您真正想要的是加载一次声音 ,然后每次按下按钮时播放它。
因此,不要在 onTouchListener 中调用 initSounds,而是在按下按钮之前在其他地方调用 initSounds。然后在你的 onTouchListener 中调用你的 playSound 方法。
最后,确保从 onLoadCompleteListener 中删除 playSound 方法调用,这样您在最初加载声音时就不会听到神秘的噪音 ;)