我有一堆声音,分配给一组按钮,我需要播放它们。我的所有声音都在资产文件夹中。然而,它不起作用。目的是: 从 assetFodler 加载并播放声音。我将从我的项目中拿出代码示例:
//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();
}
Run Code Online (Sandbox Code Playgroud)
为了避免使用大量代码行,我创建了一个加载和播放声音的基本过程:
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);
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我传递了文件(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;
Run Code Online (Sandbox Code Playgroud)
当我运行项目时,没有任何反应,logcat 说:
12-09 10:38:34.851: W/SoundPool(17331): sample 2 not READY
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激。
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();
}
Run Code Online (Sandbox Code Playgroud)
和 Onclick 按钮:
//resourcePlayer.stop();
mSoundPool.stop(mStream1);
mStream1= mSoundPool.play(mSoundPoolMap.get(RAW_1_1), streamVolume, streamVolume, 1, LOOP_1_TIME, 1f);
Run Code Online (Sandbox Code Playgroud)
我只是不想有那么多代码行,我想让它看起来不错
在使用SoundPool.setOnLoadCompleteListener播放之前,您需要检查文件是否已成功加载
将您的loadSound方法代码更改为:
public void loadSound (String strSound, int stream) {
boolean loaded = false;
mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
}
});
try {
stream= mSoundPool.load(aMan.openFd(strSound), 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Is the sound loaded already?
if (loaded) {
mSoundPool.play(stream, streamVolume, streamVolume, 1, LOOP_1_TIME, 1f);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6585 次 |
| 最近记录: |