android中soundpool的使用

来源:互联网 发布:乌鲁木齐软件开发公司 编辑:程序博客网 时间:2024/05/16 15:56
用soundpool可以播一些短的反应速度要求高的声音, 
比如游戏中的爆破声,而mediaplayer适合播放长点的。 
1. SoundPool载入音乐文件使用了独立的线程,不会阻塞UI主线程的操作。但是这里如果音效文件过大没有载入完成,我们调用play方法时可能产生严重的后果,这里Android SDK提供了一个SoundPool.OnLoadCompleteListener类来帮助我们了解媒体文件是否载入完成,我们重载 onLoadComplete(SoundPool soundPool, int sampleId, int status) 方法即可获得。 
2. 从上面的onLoadComplete方法可以看出该类有很多参数,比如类似id,是的SoundPool在load时可以处理多个媒体一次初始化并放入内存中,这里效率比MediaPlayer高了很多。 
3. SoundPool类支持同时播放多个音效,这对于游戏来说是十分必要的,而MediaPlayer类是同步执行的只能一个文件一个文件的播放。 


使用方法: 
1. 创建一个SoundPool 

  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 一般把多个声音放到HashMap中去,比如 
    soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100); 
    soundPoolMap = new HashMap<Integer, Integer>();   
    soundPoolMap.put(1, soundPool.load(this, R.raw.dingdong, 1)); 

  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)  //从完整文件路径名载入 
最后一个参数为优先级。 

3 播放 
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开始。 



几个重要的函数:

soundPool的构造函数

public SoundPool (int maxStreams, int streamType, int srcQuality)

参数:
maxStreams 同时最大播放音频个数
streamType 音频流的类型,通常使用 STREAM_MUSIC.
srcQuality the sample-rate converter quality. Currently has no effect. Use 0 for the default.

音效播放函数:
public void playSounds(int sound, int number){
    //实例化AudioManager对象,控制声音
    AudioManager am = (AudioManager)this.getSystemService(this.AUDIO_SERVICE);
    //最大音量
    float audioMaxVolumn = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    //当前音量
    float audioCurrentVolumn = am.getStreamVolume(AudioManager.STREAM_MUSIC);
    float volumnRatio = audioCurrentVolumn/audioMaxVolumn;
    //播放
    sp.play(spMap.get(sound),    //声音资源
        volumnRatio,        //左声道
        volumnRatio,        //右声道
        1,            //优先级,0最低
        number,        //循环次数,0是不循环,-1是永远循环
        1);            //回放速度,0.5-2.0之间。1为正常速度
}


原创粉丝点击