1
我有一堆声音,分配给一组按钮,我需要播放它。我所有的声音都在资产文件夹中。但是,它不起作用。 目的是:从assetFodler加载和播放,听起来。我会出来与我的项目的代码示例:从资产中加载并使用soundpool
//set up audio player
mSoundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
streamVolume = streamVolume/mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//getting files lists from asset folder
aMan = this.getAssets();
try {
filelist = aMan.list("");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
对于不有很多的代码行的目的,我创建了一个基本的程序装载和打声音:
public void loadSound (String strSound, int stream) {
try {
stream= mSoundPool.load(aMan.openFd(strSound), 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mSoundPool.play(stream, streamVolume, streamVolume, 1, LOOP_1_TIME, 1f);
}
正如你所看到的,我传递文件(stringName)和streamID。
最后,这里是我如何使用它:
case R.id.button1:
//if button was clicked two or more times, when play is still on im doing stop
mSoundPool.stop(mStream1);
loadSound(filelist[0],mStream1);
break;
当我跑项目,没有任何反应和logcat的说:
12-09 10:38:34.851: W/SoundPool(17331): sample 2 not READY
任何帮助,将不胜感激。
UPD1: 当我做这种方式,而不必LoadSound读取程序,它工作正常 下面的代码是的onCreate:
//load fx
try {
mSoundPoolMap.put(RAW_1_1, mSoundPool.load(aMan.openFd(filelist[0]), 1));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
和ONCLICK按钮:
//resourcePlayer.stop();
mSoundPool.stop(mStream1);
mStream1= mSoundPool.play(mSoundPoolMap.get(RAW_1_1), streamVolume, streamVolume, 1, LOOP_1_TIME, 1f);
我只是不想有这么多的代码行,我想让它看起来不错
很好,没有任何反应。似乎没有加载...为什么? – Daler
@Daler:因为在当前代码中执行顺序的所有内容都会在mSoundPool.load(aMan.openFd(strSound),1)之后进行一些等待。 '叫。你可以看到http://www.vogella.com/blog/2011/06/27/android-soundpool-how-to-check-if-sound-file-is-loaded/例子 –
不幸的是,我当用户点击按钮时不得有任何延迟。它必须立即播放。任何想法如何实现它?其实我可以通过使用R.raw立即播放它,但是我想从资产来做。 – Daler