iOS 播放自定义声音

自定义声音是由 iOS 系统来播放的,所以对音频数据格式有限制,可以是如下四种之一:

  1. Linear PCM
  2. MA4 (IMA/ADPCM)
  3. µLaw
  4. aLaw

对应音频文件格式是 aiffwavcaf文件,文件也必须放到 app 的 mainBundle 目录中。

自定义声音的播放时间必须在 30s 内。

可以使用 afconvert工具来处理音频文件格式,在终端中敲入如下命令就可以将一个 mp3 文件转换成 caf 文件:

afconvert /Users/apple/Desktop/Alarm.mp3 /Users/apple/Desktop/Alarm.caf -d ima4 -f caff -v

转换完成后就可以将 Alarm.caf 这个文件拖入 Xcode 工程中,编译运行项目在真机上。

需要导入头文件 

#import 

播放自定义声音

    SystemSoundID soundID;
    
    NSURL *audioUrl = [[NSBundle mainBundle] URLForResource:@"alarm" withExtension:@"caf"];
    
    AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(audioUrl), &soundID);
    
    AudioServicesPlayAlertSound(soundID);

 

关闭自定义声音

AudioServicesDisposeSystemSoundID(soundID);

 

你可能感兴趣的:(iOS 播放自定义声音)