首页 > 系统 > Android > 正文

Android使用SoundPool播放短音效

2019-12-11 20:54:45
字体:
来源:转载
供稿:网友

前言

对于Android播放一些简短音效,例如提示音,或者铃声,相对于使用MediaPlayer,SoundPool可以节省更多资源,并且可以同时播放多个音效,而且可以针对不同音效设置不同播放品质

实现

SoundPool的具体作用,就不再阐述,直接贴代码

private SoundPool.Builder spBuilder;private SoundPool soundPool;private Integer[] fmSound = FmManager.getRawAudios(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {      if (null == spBuilder) {        spBuilder = new SoundPool.Builder();        AudioAttributes.Builder builder = new AudioAttributes.Builder();        builder.setLegacyStreamType(AudioManager.STREAM_MUSIC);        spBuilder.setAudioAttributes(builder.build());        spBuilder.setMaxStreams(10);      }      if (null == soundPool) {        soundPool = spBuilder.build();      }    } else {      if (null == soundPool) {        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 10); //最多播放10个音效,格式为Steam_music,音质为10      }    }    soundPool.setOnLoadCompleteListener(this);    if (null == fmArray) {      fmArray = new SparseIntArray();    }    if (null == streamArray) {      streamArray = new SparseIntArray();    }    for (int i = 0; i < fmSound.length; i++) {      fmArray.put(i + 1, soundPool.load(this, fmSound[i], 1));  //将需要播放的资源添加到SoundPool中,并保存返回的StreamID,通过StreamID可以停止某个音效    } private void playFmByPosition(int resultId) {    if (null == soundPool || resultId < 0 || fmArray == null || fmArray.size() < 0 || streamArray == null)      return;    LogUtils.e(resultId + "------------" + fmArray.size());    if (resultId < fmArray.size()) {      if (!FmPlaying.isPlay(resultId)) {        int fmPlayId = soundPool.play(fmArray.get(resultId + 1), 1, 1, 0, -1, 1);        streamArray.put(resultId, fmPlayId);        FmPlaying.setPlay(resultId, true);      } else {        soundPool.stop(streamArray.get(resultId));        streamArray.removeAt(resultId);        FmPlaying.setPlay(resultId, false);      }    }  }  static class FmPlaying {    private static SparseBooleanArray playArray = new SparseBooleanArray();    public static boolean isPlay(int position) {      return playArray.get(position, false);    }    public static void setPlay(int position, boolean play) {      playArray.put(position, play);    }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表