【Android -- 音效】使用 SoundPool 播放音效

article/2025/10/5 22:19:40

前言

SoundPool 一般用来 播放密集,急促而又短暂的音效,比如特技音效:Duang~,游戏用得较多,你也可以为你的 APP 添加上这个音效,比如酷狗音乐进去的时候播放"哈喽,酷狗",其实这个创意还是不错的 间接的让用户知道了当前播放器的音量,不然用户一放歌,突然来了一发小苹果,引得附近 大妈起舞就不好了是吧;除了可以在音乐播放器加,你还可以在普通 APP 加上,比如收到推送 信息或者新的聊天信息,然后播放提示音,比如超级课程表新版本,加了这玩意,收到推送 信息会播放一段短促的"表表"的声音!

SoundPool 对象可以看作是一个可以从 APK 中导入资源 或者从文件系统中载入文件的样本集合。

它利用 MediaPlayer 服务为音频解码为一个原始16位 PCM流。这个特性使得应用程序可以进行流压缩,而无须忍受在播放音频时解压所带来的 CPU 负载和延时。SoundPool 使用音效池的概念来管理多个播放流,如果超过流的最大数目, SoundPool 会基于优先级自动停止先前播放的流,另外,SoundPool 还支持自行设置声音的品质、 音量、 播放比率等参数。

常用方法

1. 加载声音资源:

  • load(Context context, int resId, int priority)
  • load(String path, int priority)
  • load(FileDescriptor fd, long offset, long length, int priority)
  • load(AssetFileDescriptor afd, int priority)
  • 上述方法都会返回一个声音的ID,后面我们可以通过这个ID来播放指定的声音

参数介绍:

  • context:上下文
  • resId:资源id
  • priority:没什么用的一个参数,建议设置为1,保持和未来的兼容性
  • path:文件路径
  • FileDescriptor:貌似是流吧,这个我也不知道
  • AssetFileDescriptor:从asset目录读取某个资源文件,用法: AssetFileDescriptor descriptor = - assetManager.openFd(“biaobiao.mp3”);

2. 播放控制:

  • play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)

参数介绍:

  • soundID:Load()返回的声音ID号
  • leftVolume:左声道音量设置
  • rightVolume:右声道音量设置
  • priority:指定播放声音的优先级,数值越高,优先级越大。
  • loop:指定是否循环:-1表示无限循环,0表示不循环,其他值表示要重复播放的次数
  • rate:指定播放速率:1.0的播放率可以使声音按照其原始频率,而2.0的播放速率,可以使声音按照其 原始频率的两倍播放。如果为0.5的播放率,则播放速率是原始频率的一半。播放速率的取值范围是0.5至2.0。

3. 资源释放:

可以调用 release() 方法释放所有 SoundPool 对象占据的内存和资源,当然也可以根据声音 ID 来释放!

实例

在这里插入图片描述
1. 实现目标

  • 播放音频文件,播放完即停止
  • 播放音频文件,循环播放

2. 布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><com.hjq.bar.TitleBarandroid:id="@+id/title_bar"android:layout_width="match_parent"android:background="@color/teal_200"android:layout_height="?android:attr/actionBarSize"app:title="SoundPool 播放音频"app:titleStyle="bold"app:titleSize="18sp"app:backButton="false"app:titleColor="@color/white"/><Buttonandroid:id="@+id/btn_sound_one"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:text="音频 1" /><Buttonandroid:id="@+id/btn_sound_two"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:text="音频 2" /><Buttonandroid:id="@+id/btn_sound_three"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:text="音频 3" /><Buttonandroid:id="@+id/btn_sound_four"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:text="音频 4" /></LinearLayout>

3. 新建 raw 目录,将所需要播放的音频文件放入
在这里插入图片描述
4. 工具类

/*** Created on 2022/6/30 11:31* SoundPool 铃声尽量不要超过1M** @author Gong Youqiang*/
public class SoundPlayerUtils {private static final String TAG = "SoundPlayerUtils";public enum RingerTypeEnum {SOUND_ONE,SOUND_TWO,SOUND_THREE,SOUND_FOUR}private Context context;private SoundPool soundPool;private AudioManager audioManager;private int streamId;private int soundId;private boolean loop;private RingerTypeEnum ringerTypeEnum;private boolean isRingModeRegister = false;private int ringMode = -1;private static SoundPlayerUtils instance = null;private RingModeChangeReceiver ringModeChangeReceiver;public static SoundPlayerUtils getInstance() {if(instance == null) {synchronized (SoundPlayerUtils.class) {if(instance == null) {instance = new SoundPlayerUtils();}}}return instance;}public SoundPlayerUtils() {this.context = MyApp.CONTEXT;//全局上下文对象,getApplicationContext();}public synchronized void play(RingerTypeEnum type) {Log.e(TAG, "play type->" + type.name());this.ringerTypeEnum = type;int ringId = 0;switch (type) {case SOUND_ONE:ringId = R.raw.sound_01;loop = false;//是否重复播放铃声break;case SOUND_TWO:ringId = R.raw.sound_02;loop = true;break;case SOUND_THREE:ringId = R.raw.sound_03;loop = false;break;case SOUND_FOUR:ringId = R.raw.sound_04;loop = true;break;}if(ringId != 0) {play(ringId);}}public void stop() {Log.e(TAG, "stop");if (soundPool != null) {if (streamId != 0) {soundPool.stop(streamId);streamId = 0;}if (soundId != 0) {soundPool.unload(soundId);soundId = 0;}}if (isRingModeRegister) {registerVolumeReceiver(false);}}private void play(int ringId) {initSoundPool();if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) {soundId = soundPool.load(context, ringId, 1);}}private void initSoundPool() {stop();if (soundPool == null) {soundPool = new SoundPool(1, AudioManager.STREAM_RING, 0);soundPool.setOnLoadCompleteListener(onLoadCompleteListener);audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);ringMode = audioManager.getRingerMode();}registerVolumeReceiver(true);}SoundPool.OnLoadCompleteListener onLoadCompleteListener = new SoundPool.OnLoadCompleteListener() {@Overridepublic void onLoadComplete(SoundPool soundPool, int sampleId, int status) {if (soundId != 0 && status == 0) {if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) {int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_RING);streamId = soundPool.play(soundId, curVolume, curVolume, 1, loop ? -1 : 0, 1f);}}}};private void registerVolumeReceiver(boolean register){if (ringModeChangeReceiver == null) {ringModeChangeReceiver = new RingModeChangeReceiver() ;}if (register) {isRingModeRegister = true;IntentFilter filter = new IntentFilter() ;filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION) ;context.registerReceiver(ringModeChangeReceiver, filter) ;} else {context.unregisterReceiver(ringModeChangeReceiver);isRingModeRegister = false;}}private class RingModeChangeReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {if (ringMode != -1 && ringMode != audioManager.getRingerMode()&& intent.getAction().equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) {ringMode = audioManager.getRingerMode();play(ringerTypeEnum);}}}
}

5. 使用

public class MainActivity extends BaseActivity {@Overrideprotected int getLayoutId() {return R.layout.activity_main;}@Overrideprotected void initView() {}@OnClick({R.id.btn_sound_one,R.id.btn_sound_two,R.id.btn_sound_three,R.id.btn_sound_four})public void clicked(View view) {switch (view.getId()) {case R.id.btn_sound_one:SoundPlayerUtils.getInstance().play(SoundPlayerUtils.RingerTypeEnum.SOUND_ONE);break;case R.id.btn_sound_two:SoundPlayerUtils.getInstance().play(SoundPlayerUtils.RingerTypeEnum.SOUND_TWO);break;case R.id.btn_sound_three:SoundPlayerUtils.getInstance().play(SoundPlayerUtils.RingerTypeEnum.SOUND_THREE);break;case R.id.btn_sound_four:SoundPlayerUtils.getInstance().play(SoundPlayerUtils.RingerTypeEnum.SOUND_FOUR);break;}}}

http://chatgpt.dhexx.cn/article/0c2tUsLk.shtml

相关文章

SoundPool播放音效

强调&#xff01;&#xff01;&#xff01;以下只是我个人看法&#xff0c;如有错误的地方请文明指出&#xff0c;如有其他看法请耐心讨论&#xff0c;如有看不懂可以参考其他有关博客&#xff0c;最后如有想喷的出门左转不谢。 上次有提到用MediaPlayer来播放音频&…

Vscode编译调试C++程序

一、简介 本文讲述在windows平台下在Vscode中使用g编译本地C程序&#xff0c;并使用gdb调试的方法。可能有些朋友会说&#xff1a;windows上不是已经有visual studio这个最强IDE了吗&#xff0c;为什么还要用Vscode调试&#xff1f;是的&#xff0c;确实没错&#xff0c;单纯用…

vscode使用visual studio编译工具MSVC构建C++工程

准备工作 vscode软件visual studio软件 添加头文件到配置中 因为要使用到win10的开发工具包&#xff0c;因此必须让其找到其头文件 ctrlshiftp打开命令搜索&#xff0c;输入c json 然后打开配置文件&#xff0c;加入路径 其中一个是msvc的工具包&#xff0c;还有一个是win1…

vs code编译器的使用

1.插件的安装 在vs code左侧可以看到有拓展&#xff0c;然后可以搜索你想要的插件&#xff0c;如图所示&#xff1a; 2.插件列表 名称 简述 Auto Close Tag 自动闭合HTML标签 Auto Import Typescript自动import提示 Auto Rename Tag 修改HTML标签时&#xff0c;自动修改匹…

vs编译器教程

本次主要介绍的是如何使用visual studio 2019编译c语言代码。 安装好vs 2019后&#xff0c;打开进入到此界面 此时我们点击创建新项目进入到 再点击第一个选项&#xff1a;空项目&#xff0c;进入下一步 对所创建的项目进行命名&#xff0c;位置尽量不要放在C盘。然后下一步 此…

在vs里配置其他编译器

我们都知道vs是微软旗下的集成开发环境&#xff0c;我们用它来写c也是非常好的&#xff0c;不过因为各种原因&#xff0c;可能各位需要其他编译器但是又不想换ide。 其实vs可以安装任何编译器&#xff0c;我们今天介绍简单的安装clang编译器 首先我们需要找到vs所在文件夹 我们…

VSCode 的C++编译

0. 参考文档 0.1. 官方参考 由于C在不同平台上编译使用的编译器不同&#xff0c;所以我们先将官网针对不同平台的编译文档摘录出来&#xff0c;以便大家参考&#xff1a; 0.0.1. Linux平台使用GCC 参考&#xff1a; https://code.visualstudio.com/docs/cpp/config-linux …

关于vs编译器的一些认识

.vcproject 后缀 是一个项目里面的一个单独的子解决方案,相当于一个小模块 .sln 后缀 是整个项目的启动点 菜单里面的生成:相当于linux的编译 如图所示 输出目录 :就是生成(编译)后的 exe文件或者 dll文件,lib文件所在的目录 目标文件名:就是编译后的文件名字 目标文件…

C语言编辑器的使用(VS)

选择编辑器 编辑器介绍VS的使用 编辑器介绍 1&#xff0c;什么是编辑器&#xff08;即开发环境&#xff09; 所谓的开发环境就是指一个基本硬件和宿主软件的基础上&#xff0c;为支持系统软件和应用软件的工程化开发&#xff0c;维护而使用的一组软件。 2&#xff0c;Visual S…

Visual Studio Code编译运行C/C++程序

参考网站&#xff1a;https://www.cnblogs.com/TAMING/p/8560253.html 使用code runner 插件 code runner插件默认的c/c编译器是gcc/g,需要提前安装好并且设置好环境变量&#xff0c;通常选择MinGW或者MinGW-w64&#xff0c;建议选mingw-w64 安装好并且设置好二者中的一个,并…

vs code如何编译C语言?

vs code 编译C/C语言 C/C语言 文章目录 vs code 编译C/C语言安装 Vs Code安装 C/C扩展安装 Mingw-w64配置环境变量检查 Min GW是否安装成功使用Hello World如何编译多个c文件代码?如何修改默认编译文件名&#xff1f;如何编译 .o 文件&#xff1f;如何输出.txt文件&#xff1f…

VS Code编译C/C++

C/C环境的配置要比python的复杂许多&#xff0c;好几个配置文件要写。 一、编译C/C的环境一般都是集成在我们的编辑器中的&#xff0c;如果电脑上有codeblock和dev c的读者可以去安装路径下找找MinGW文件夹&#xff0c;可以不用重复下载。而没有的读者则需要下载MinGW 二、配置…

使用VS Code 编译运行C/C++程序

文章目录 安装C/C编译器验证C/C开发环境安装插件 创建C文件运行C文件 调试创建tasks.json文件构建C文件创建launch.json文件调试C文件 总结 安装C/C编译器 macOS与主流的发行版Linux系统都自带了C/C编译器(gcc和g)&#xff0c;而对于Windows&#xff0c;我们需要通过Mingw-w64…

【C++】各版本标准与gcc、vs编译器对应关系

c常用的编译场景一般是linux或windows&#xff0c;linux通常使用Mingw中的gcc/g编译器&#xff0c;Windows通常使用visual studio IDE中的微软编译器&#xff0c;随着c11及以上标准的普及&#xff0c;再编译器遇到这些新特性的时候&#xff0c;如果编译器版本过低&#xff0c;那…

Visual Studio Code(VSCode) 编辑/编译/调试 C++ 代码

前言 最近想要切换编辑工具&#xff0c;之前工作中使用过 Source Insight&#xff0c;Eclipse&#xff0c;CLion 来写 C 代码。目前来说 Source Insight 已经非常古老&#xff0c;只有编写代码还说得过去&#xff0c;编译、调试方面都不行。Eclipse 使用的时间最长&#xff0c;…

你是真的“C”——Visual Studio 2022(VS2022)编译器 -—实用调试技巧

你是真的“C”——Visual Studio 2022&#xff08;VS2022&#xff09;编译器 -—实用调试技巧&#x1f60e; 前言&#x1f64c;1. 什么是bug&#xff1f;&#x1f64c;2. 调试是什么&#xff1f;有多重要&#xff1f;&#x1f64c;2.1 调试是什么&#xff1f;2.2 调试的基本步骤…

c/c++ ------visualstudio编译器的使用

一个编译器而已 visualstudio是一个编译器而已(简称vs) 可视化的代码编译器&#xff1b;可视化的代码编辑器&#xff1b;方便的代码调试器&#xff1b;做好了windows操作系统拥有的库文件接口&#xff1b; 养成一个好的习惯&#xff1a; 编译目录&#xff1b;源码目录&#xff…

VS编译器的简单操作

目录 c语言的百度定义​ vs编译器的简单使用 第一个代码 什么是main函数 当运行结果一闪而过怎么办 c语言的百度定义 vs编译器的简单使用 要写一个代码首先要创建一个新项目&#xff0c;点击创建一个新项目&#xff0c;然后就有这样一个画面 语言选择c&#xff0c;选择空项目…

编译器的差别gcc和VS

问题的由来是我写了一个排序算法程序&#xff0c;在gcc编译器下运行&#xff0c;发现结果有问题&#xff0c;然后开展的寻找错误解决问题 这是我写的一个简单的插入排序算法 #include <stdio.h>//直接插入法排序函数主体 //参数1&#xff1a;待排序的序列 //参数2&…

Visual Studio编译器使用总结

经历过各种坑。安装坑&#xff0c;使用坑&#xff0c;配置坑。 今天抽空把总结写一下。 下面例子为vs2015举例。 大部分公司因为时间的问题&#xff0c;基本项目都是从vs2015版本进行开发的。后续为了统一&#xff0c;也建议大家用vs2015创建工程。 一、安装篇 vs2017-19版本…