这篇文章给大家介绍如何在Android中使用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); } }
关于如何在Android中使用SoundPool播放音效就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。