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:文件需要自己导入

转载于:https://www.cnblogs.com/chixuedong/p/5370070.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值