1、以一个点击按钮播放音效为例
#import
2、创建枚举值
typedef NS_ENUM(NSInteger, VoiceType) { VoiceTypeIsWav = 0, // wav VoiceTypeIsMp3 = 1, // mp3 VoiceTypeIsAPE = 2, // ape VoiceTypeIsOther = 3 // 其他 }; NSString *const VoiceTypeStringMap[] = { [VoiceTypeIsWav] = @"wav", [VoiceTypeIsMp3] = @"mp3", [VoiceTypeIsAPE] = @"ape", [VoiceTypeIsOther] = @"Other" };
3、播放音频文件方法抽取
/************ 播放音效 *****************************/ - (void)playSoundEffect:(NSString *)name withType:(VoiceType)type { // 播放扫描二维码的声音 SystemSoundID soundID; NSString *strSoundFile = [[NSBundle mainBundle] pathForResource:name ofType:VoiceTypeStringMap[type]]; AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:strSoundFile],&soundID); AudioServicesPlaySystemSound(soundID); }
4、按钮点击播放音效
/************ 点击开关灯按钮就会调用 *****************************/ - (void)OpenOrClosedLamp:(UIButton *)button { // 播放音效 [self playSoundEffect:@"btn_press_voice_2" withType:VoiceTypeIsWav]; }