zoukankan      html  css  js  c++  java
  • SoundPool 播放短声音

    SoundPool 最大只能申请1M的内存空间,只能用一些很短的声音片段,而不是用它来播放歌曲或者做游戏背景音乐。

    使用 SoundPool 播放短声音实现步骤如下:

    // 创建SoundPool实例, 指定最大可以加载声音为3个
    
    SoundPool soundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
    
    // 分别加载三个不同的声音
    
    int shoot1ID = soundPool.load(this, R.raw.shoot1, 1);
    
    int shoot2ID = soundPool.load(this, R.raw.shoot2, 1);
    
    int shoot3ID = soundPool.load(this, R.raw.shoot3, 1);
    
    // 根据加载时获取的id播放对应的声音
    
    soundPool.play(shoot1ID, 1, 1, 1, 0, 1);
    
    soundPool.play(shoot2ID, 1, 1, 1, 0, 1);
    
    soundPool.play(shoot3ID, 1, 1, 1, 0, 1);
    

    在onDestory释放资源:

    soundPool.release();

    注意:

    遇到一个奇怪的问题,soundpool.play()在部分华为和小米手机上只能发出一次声音,后面调用soundpool.play()居然没有声音发出了,可是这个问题只是在部分手机上出现而已,部分华为的也可以继续发声,魅族的也可以。经过研究分析认为应该是我在activity 的oncreate方法里面加载完文件后,后面调用了一次soundpool.play()播放了文件,然后由于部分手机的内存太小或者手机系统太优,自动释放内存把资源释放掉了,这才导致后面调用soundpool.play()不发出声音。最后我是这样解决的:在需要播放的地方重新加载文件,让它加载完成后再播放,具体如下:

      pool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                    @Override
                    public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                        soundPool.play(shoot1ID, 1, 1, 0, 0, 1);
                    }
     });
  • 相关阅读:
    Spring Boot:自动配置原理
    centos7安装zookeeper
    spring集成RabbitMQ
    centos7安装RabbitMQ
    centos7安装MongoDB4.0(yum安装)
    nginx日志分割
    centos7 yum安装nginx
    centos7使用cronolog分割tomcat8.5的catalina.out日志
    ubuntu18安装微信
    idea打开dashboard
  • 原文地址:https://www.cnblogs.com/loaderman/p/6421562.html
Copyright © 2011-2022 走看看