iOS之播放音效(AVFoundation)
生活随笔
收集整理的這篇文章主要介紹了
iOS之播放音效(AVFoundation)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
前提需要導入<AVFoundation/AVFoundation.h>框架 #import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "CXDAudioTool.h" //自定義播放工具類,根據(jù)傳入音頻文件名,設置聲音@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) {// 根據(jù)音效文件,來生成SystemSoundIDNSURL *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 CXDAudioToolstatic NSMutableDictionary *_soundIDs;+ (void)initialize {_soundIDs = [NSMutableDictionary dictionary]; }+ (void)playSoundWithSoundname:(NSString *)soundname {// 1.定義SystemSoundIDSystemSoundID 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); }@endps:文件需要自己導入
轉(zhuǎn)載于:https://www.cnblogs.com/chixuedong/p/5370070.html
總結(jié)
以上是生活随笔為你收集整理的iOS之播放音效(AVFoundation)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。