使用 Audio Toolbox 的 Audio Services 播放 AAC

使用 Audio Toolbox 的 Audio Services 播放 AAC

  • [使用 Audio Toolbox 的 Audio Services 播放 AAC](#使用 Audio Toolbox 的 Audio Services 播放 AAC)

使用 Audio Toolbox 的 Audio Services 播放 AAC

主要分为 3 步:

  1. 使用 AudioServicesCreateSystemSoundID 创建系统声音。
  2. 使用 AudioServicesAddSystemSoundCompletion 设置回调。
  3. 使用 AudioServicesPlaySystemSound 开始播放。

关于 AudioServicesPlaySystemSound 函数:

此功能播放短声音(持续时间为 30s 或更短)。由于声音可能会播放几秒钟,此功能是异步执行的。要了解声音何时完成播放,调用 AudioServicesAddSystemSoundCompletion 函数来注册回调函数。

在某些 iOS 设备上,可以通过 AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) 来调用振动。在其他 iOS 设备上,使用该常量调用此函数没有任何作用。

以下是该函数能播放的音频文件的限制:

  • No longer than 30 seconds in duration
  • In linear PCM or IMA4 (IMA/ADPCM) format
  • Packaged in a .caf, .aif, or .wav file

但实际上,AAC 文件也是能正常播放的,此外,该函数还有诸多限制:

  • 声音在当前系统音频音量下播放,没有编程音量控制。
  • 声音立即播放。
  • 不支持循环和立体声定位。
  • 无法同时播放,一次只能播放一个声音。
  • 声音在设备扬声器上本地播放,不使用音频路由。

核心代码:

objc 复制代码
- (void)btnClick:(UIButton *)sender
{
    self.mButton.hidden = YES;
    NSURL *audioUrl = [[NSBundle mainBundle] URLForResource:@"music" withExtension:@"aac"];
    SystemSoundID soundID;
    // create a system sound object
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)audioUrl, &soundID);
    // register a callback function that is invoked when a specified system sound finishes playing
    AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, &playCallback, (__bridge void *_Nullable)(self));
    // play a system sound object
    AudioServicesPlaySystemSound(soundID);
}

void playCallback(SystemSoundID ssID, void  *clientData)
{
    ViewController *vc = (__bridge ViewController *)clientData;
    vc->_mButton.hidden = NO;
}

项目地址:https://github.com/UestcXiye/AudioToolboxSystemSound。

相关推荐
2601_961593424 小时前
Rust 开发环境配置繁琐?RustRover 开箱即用搞定编码调试
开发语言·后端·macos·rust
在水一缸5 小时前
拒绝被打扰:深度解析 macOS 进程守护与“反自动启动”攻防战
macos·策略模式·用户体验·进程守护·自动启动·系统权限
REDcker10 小时前
macOS 挂载 Linux 远程目录详解
linux·运维·macos
2601_9615934210 小时前
Mac 上搭建Linux环境吗?VMware + CentOS Stream 9 镜像快速部署
linux·运维·ide·macos·centos
陪我去看海12 小时前
受够了 AI 写完代码留下一堆端口?我做了一个端口管理App!
前端·macos·vibecoding
发光的沙子13 小时前
FPGA----配置根文件系统ip和mac地址
网络协议·tcp/ip·macos
2601_9615934215 小时前
Mac 虚拟机跑 Linux 选哪个?CentOS 8 稳定版适配方案
linux·macos·centos
IT·陈寒16 小时前
macOS 安装 Claude Code 全流程
人工智能·macos·策略模式
七牛云行业应用16 小时前
Codex 桌面端一直 Reconnecting 5/5?根因分析与逐步修复指南(macOS/Windows)
windows·macos