首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何创建多个Soundpool?

如何创建多个Soundpool?
EN

Stack Overflow用户
提问于 2014-01-12 02:16:01
回答 1查看 677关注 0票数 0

我的安卓应用程序中有一个SoundPool,但我不知道如何为2个或更多的SoundPool实例编写代码。有没有办法为多个SoundPools重新编写这段代码?

代码语言:javascript
复制
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    View view = findViewById(R.id.button1);
    view.setOnTouchListener(this);

    // Set the hardware buttons to control the music
    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
    // Load the sound
    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener()

    {
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId,
                int status) {
            loaded = true;

        }
    });

    soundID = soundPool.load(this, R.raw.sound1, 1);

}
public boolean onTouch( View v, MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        // Getting the user sound settings
        AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        float actualVolume = (float) audioManager
                .getStreamVolume(AudioManager.STREAM_MUSIC);
        float maxVolume = (float) audioManager
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        float volume = actualVolume / maxVolume;
        // Is the sound loaded already?
        if (loaded) {
            soundPool.play(soundID, volume, volume, 1, 0, 1f);
            Log.e("Test", "Played sound");
        }
    }
    return false;
}
EN

回答 1

Stack Overflow用户

发布于 2014-05-18 05:57:08

尝试:

代码语言:javascript
复制
// 8 soundpools
SoundPool[] soundPool = new SoundPool[8];
int[] soundID = new int[8];

// You can have more that one set per sound if need, just make more raw sound 
// arrays with different sounds.

// 8 sounds per soundpool
int[] rawSounds = new int[]{ R.id.sound1, R.id.sound2, R.id.sound3,
                             R.id.sound4, R.id.sound5, R.id.sound6,
                             R.id.sound7, R.id.sound8 };

boolean[] loaded = new boolean[8];

// Go through each soundpool
for(int i = 0; i < 8; i++)
{
    soundPool[i] = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);

    // 8 sounds in one soundpool
    for(int h = 0; h < 8; h++)
    {
        soundID[i] = soundPool.load(this, rawSounds[i], 1); 
    }

    soundPool[i].setOnLoadCompleteListener(new OnLoadCompleteListener()
    {
        Override
        public void onLoadComplete(SoundPool soundPool, int sampleId,
                int status) 
        {
            // One boolean per soundpool
            loaded[i] = true;
        }
    });
}

然后使用for循环查看正在按下的是哪种声音,并使用soundIDi.play播放声音。

希望这能有所帮助,尽管有点晚!)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21066038

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档