首先导入音频文件到项目中
OC的代码如下:
//播放音频
#import <AudioToolbox/AudioToolbox.h>
@property (readonly)SystemSoundID soundFileObject;
NSString *path = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"/high_alarm.wav"];AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&(_soundFileObject));AudioServicesPlaySystemSound(_soundFileObject);//开启震动AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);
SWift版本:
第一种方案:wav格式
private var soundFileObject: SystemSoundID = 0let path = "\(Bundle.main.resourcePath ?? "")\("/high_alarm.wav")"AudioServicesCreateSystemSoundID(URL(fileURLWithPath: path) as CFURL, &soundFileObject)AudioServicesPlaySystemSound(soundFileObject)
第二种方案:(系统默认的)
var anId = 0if soundID != nil {anId = Int(soundID!)!}else{anId = 1000}AudioServicesPlaySystemSound(SystemSoundID(anId))
完毕