Android开发经验谈android 开发程序员

Android使用SoundPool播放短音效

2017-06-12  本文已影响401人  T9的第三个三角
前言

对于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);
        }
    }```
上一篇下一篇

猜你喜欢

热点阅读