iOS之播放音效(AVFoundation)
前提需要导入<AVFoundation/AVFoundation.h>框架
#import "ViewController.h" #import <AVFoundation/AVFoundation.h> #import "CXDAudioTool.h" //自定义播放工具类,根据传入音频文件名,设置声音 @interface ViewController () @property (nonatomic, assign) SystemSoundID soundID; /** 存放音效文件 */ @property (nonatomic, strong) NSMutableDictionary *soundIDs; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } - (IBAction)buyao { [CXDAudioTool playSoundWithSoundname:@"buyao.wav"]; } - (IBAction)bigWang:(id)sender { [CXDAudioTool playSoundWithSoundname:@"m_17.wav"]; } - (IBAction)smallWang:(id)sender { [CXDAudioTool playSoundWithSoundname:@"m_16.wav"]; } #pragma mark - 点击屏幕背景音效 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { AudioServicesPlayAlertSound(self.soundID); } ///懒加载 - (SystemSoundID)soundID { if (_soundID == 0) { // 根据音效文件,来生成SystemSoundID NSURL *url = [[NSBundle mainBundle] URLForResource:@"win.aac" withExtension:nil]; CFURLRef urlRef = (__bridge CFURLRef)(url); AudioServicesCreateSystemSoundID(urlRef, &_soundID); } return _soundID; } ///懒加载 - (NSMutableDictionary *)soundIDs { if (_soundIDs == nil) { _soundIDs = [NSMutableDictionary dictionary]; } return _soundIDs; } @end
以下是自定义工具类 CXDAudioTool
#import <Foundation/Foundation.h> @interface CXDAudioTool : NSObject + (void)playSoundWithSoundname:(NSString *)soundname; @end
#import "CXDAudioTool.h" #import <AVFoundation/AVFoundation.h> @implementation CXDAudioTool static NSMutableDictionary *_soundIDs; + (void)initialize { _soundIDs = [NSMutableDictionary dictionary]; } + (void)playSoundWithSoundname:(NSString *)soundname { // 1.定义SystemSoundID SystemSoundID soundID = 0; // 2.从字典中取出对应soundID,如果取出是nil,表示之前没有存放在字典 soundID = [_soundIDs[soundname] unsignedIntValue]; if (soundID == 0) { CFURLRef url = (__bridge CFURLRef)[[NSBundle mainBundle] URLForResource:soundname withExtension:nil]; AudioServicesCreateSystemSoundID(url, &soundID); // 将soundID存入字典 [_soundIDs setObject:@(soundID) forKey:soundname]; } // 3.播放音效 AudioServicesPlaySystemSound(soundID); } @end
ps:文件需要自己导入