我正在尝试用SoundPool执行一个mp3文件.我用SoundPool.load加载了mp3,但是当我尝试使用SoundPool.play不起作用而且没有抛出任何异常.我正在使用API21.
我该如何解决?
我正在尝试这个.
public class CustomSoundPool {
//SDK Version
public SoundPool getSoundPool(){
SoundPool sounds = null;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
sounds = new SoundPool.Builder()
.setAudioAttributes(attributes)
.build();
}else{
sounds = new SoundPool(5,AudioManager.STREAM_MUSIC,0);
}
return sounds;
}
}
/** play sound with error or success */
private void playSound(){
SoundPool sound = new CustomSoundPool().getSoundPool();
if(resposta.getValor() == 1){
int soundId = sound.load(getView().getContext(), R.raw.sucesso, 1);
sound.play(soundId, 1, 1, 0, 0, 1);
}else{
int soundId = sound.load(getView().getContext(), R.raw.erro, 1);
sound.play(soundId, 1, 1, 0, 0, 1);
}
sound.release();
}
Run Code Online (Sandbox Code Playgroud)
你发布SoundPool得太早了.稍后发布,即以onDestroy方法发布Activity.现在,SoundPool在释放对象使用的所有内存和本机资源之前,声音将没有足够的时间播放.此外,你试图在它实际设法加载之前快速播放声音.play在加载声音之前无法使用.使用SoundPool.OnLoadCompleteListener#onLoadComplete等到声音加载并且内部听众播放您的声音.
SoundPool soundPool;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
soundPool = new SoundPool.Builder()
.setAudioAttributes(attributes)
.build();
}
else {
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
}
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
soundPool.play(sampleId, 1.0f, 1.0f, 0, 0, 1.0f);
}
});
soundPool.load(this, R.raw.sucesso, 1);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3921 次 |
| 最近记录: |