Android的SoundPool

开发Android软件中我们可能经常需播放多媒体声音文件,一般使用MediaPlayer类但该类占用资源较多,对于游戏等应用可能不是很适合,SoundPool类在SDKandroid.media.SoundPool,顾名思义是声音池的意思。主要播放一些较短的声音片段,可以从程序的资源或文件系统加载,相对于MediaPlayer类可以做到使用较少的CPU资源和较短的反应延迟。

            SoundPool和其他声音播放类相比,其特点是可以自行设置声音的品质、音量、播放比率等参等。并且它可以同时管理多个音频流,每个流都有独自的ID,对某个音频流的管理都是通过ID进行的。

         SoundPool基本使用方法:
              1. 创建一个SoundPool 
                 创建一个SoundPool对象:new SoundPool(int maxStreams, int streamType, int srcQuality);

                public SoundPool(int maxStream, int streamType, int srcQuality) 
                maxStream —— 同时播放的流的最大数量 
                  streamType —— 流的类型,一般为STREAM_MUSIC(具体在AudioManager类中列出) 
                  srcQuality —— 采样率转化质量,当前无效果,使用0作为默认值 
                  eg. 
                    SoundPool soundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);

                       创建了一个最多支持3个流同时播放的,类型标记为音乐的SoundPool。
          2、 从资源或者文件载入音频流: load(Context context, int resId, int priority);

                    soundpool的加载: 
                       int  load(Context context, int resId, int priority)  //从APK资源载入 
                       int  load(FileDescriptor fd, long offset, long length, int priority)  //从FileDescriptor对象载入 
                       int  load(AssetFileDescriptor afd, int priority)  //从Asset对象载入 
                       int  load(String path, int priority)  //从完整文件路径名载入 
                                  最后一个参数为优先级。

                         一般把多个声音放到HashMap中去,比如 
                         soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100); 
                         soundPoolMap = new HashMap<Integer, Integer>();   
                         soundPoolMap.put(1, soundPool.load(this, R.raw.dingdong, 1));
          3、  播放声音play (int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate);

                     play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate) ,

                       其中leftVolume和rightVolume表示左右音量,

                            priority表示优先级,

                            loop表示循环次数,

                           rate表示速率,如  //速率最低0.5最高为2,1代表正常速度 
                    sp.play(soundId, 1, 1, 0, 0, 1); 
                    而停止则可以使用 pause(int streamID) 方法,这里的streamID和soundID均在构造SoundPool类的

                    第一个参数中指明了总数量,而id从0开始。

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

   2. SoundPool提供了pausestop方法,但这些方法建议最好不要轻易使用,因为有些时候它们可能会使你的程序莫名其妙的终止。Android开发网建议使用这两个方法的时候尽可能多做测试工作,还有些朋友反映它们不会立即中止播放声音,而是把缓冲区里的数据播放完才会停下来,也许会多播放一秒钟。

   3. SoundPool的效率问题。其实SoundPool的效率在这些播放类中算是很好的了,这可能会影响用户体验。也许这不能管SoundPool本身,因为到了性能比较好的Droid中这个延迟就可以让人接受了。

原文地址:https://www.cnblogs.com/androidsj/p/3947488.html