android 中播放声音要注意的细节

 1.使用MediaPlayer播放游戏音乐
    创建MediaPlayer对象 将Context与资源文件传入。 
     /**创建MediaPlayer对象**/
    MediaPlayer mMediaPlayer = MediaPlayer.create(mContext, R.raw.v3);
    /**设置为循环播放**/
    mMediaPlayer.setLooping(true);
   
   //判断声音是否正在播放,如果没有播放则开始播放游戏音乐
    if(!mMediaPlayer.isPlaying()) {
        mMediaPlayer.start();
    }
    //判断声音是否正在播放,如果正在播放则停止播放游戏音乐。
     /**关闭音乐**/
    if(mMediaPlayer.isPlaying()) { 
        mMediaPlayer.stop();
    }
    这里强调一下MediaPlayer同一时间只能播放一个音乐。
 
 
 
2.使用SoundPool播放游戏音效
 
Soundpool的加载:
 
  int  load(Context context, int resId, int priority)  //从资源中载入 比如 R.raw.id
  int  load(FileDescriptor fd, long offset, long length, int priority)  //从FileDescriptor 对象载入
  int  load(AssetFileDescriptor afd, int priority)  //从AssetFileDescriptor 对象载入
  int  load(String path, int priority)  //从完整文件路径名载入 第二个参数为优先级。
  
      /**创建一个声音播放池**/
    //参数1为声音池同时播放的流的最大数量 
    //参数2为播放流的类型
    //参数3为音乐播放效果
    mSoundPool = new SoundPool(2,AudioManager.STREAM_MUSIC,100);
    //读取音效
    mSound_0 = mSoundPool.load(mContext, R.raw.voic_p1, 0);
    mSound_1 = mSoundPool.load(mContext, R.raw.voic_p1, 0);
 
播放音效
play (int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)
leftVolume 表示对左音量设置 rightVolume 表示右音量设置 , loop 表示 循环次数 rate表示速率最低0.5最高为2,1代表正常速度
  
  mSoundPool.play(mSound_0, 1, 1, 0, 0, 1);
原文地址:https://www.cnblogs.com/zhangguangtao/p/3010369.html