从资产加载和播放soundpool

时间:2012-12-09 05:56:47

标签: android soundpool

我有一堆声音,分配给一组按钮,我需要播放。我的所有声音都在资产文件夹中。但是,它不起作用。 目的是: 从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();
    }

为了没有很多代码行,我为加载播放声音创建了一个基本程序:

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);

我只是不想拥有这么多代码行,我想让它看起来不错

1 个答案:

答案 0 :(得分:2)

在使用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);
    }
}