iOS播放短的音效

时间:2023-03-09 07:59:35
iOS播放短的音效

在IOS中,有的时候需要播放很简短的声音文件,比如系统声音等,我们需要使用到下面的方式来播放声音:

  1. // 一、引入头文件
  2. #import <AudioToolbox/AudioToolbox.h>
  1. // 二、声明一个声音源ID,会与一个声音文件唯一对应
  2. SystemSoundID _soundID;
  1. // 三、播放音频需要先注册声音源
  2. NSURL *soundUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sound" ofType:@"wav"]];
  3. AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundUrl, &_soundID)
  1. // 四、在需要播放声音的时候,播放声音
  2. AudioServicesPlaySystemSound(_soundID)
    1. // 五、不再使用声音的时候,需要释放掉声音资源
    2. AudioServicesDisposeSystemSoundID(_soundID)