音效播放
简介
音效:就是指由声音所制造的效果,是指为增进一场面之真实感、气氛或戏剧讯息,而加于声带上的杂音或声音
- 音效的特点
- 音效一般只是一个很短的声音,一般就1-2s左右,最多只支持30s
- 音效有两种,一种是不带振动,一种是带振动(需要真机)
- iOS中音效播放是由非常底层的AudioToolbox框架来负责的,该类专门负责播放短声音
- 该框架在使用时一般无需单独导入,只需要导入
<AVFoundation/AVFoundation.h>即可,因为AVFoundation框架内部已导入<AudioToolbox> - iOS系统中目前支持的音频格式有17种
![iOS音频格式]()
代码
#import "ViewController.h"
//导入多媒体框架
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@property(nonatomic, assign)uint32_t soundid;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//调用播放音效不带振动效果的方法
//[self playWithSoundName:@"lose.aac" andAlert:NO];
//调用播放音效带振动效果的方法(必须真机调试)
[self playWithSoundName:@"buyao.wav" andAlert:YES];
}
#pragma mark - 播放音效的方法
/**
播放音效
@param name 音效的文件名(带后缀)
@param alert 是否振动
*/
- (void)playWithSoundName:(NSString *)name andAlert:(BOOL)alert {
//1. 创建音效类
//1.1 获取包中音效文件的url路径
NSURL *url = [[NSBundle mainBundle] URLForResource:name withExtension:nil];
//1.2 创建系统音效soundID
SystemSoundID soundID = 0;
//1.3 音效的播放是由系统底层来播放(基于C的接口)
///传入音频路径url就会和soundID进行绑定,之后需要播放的时候, 只需要调用soundID, 就能找到对应的URL地址
///这样做的好处就是soundID对音效的一个缓存,当音效文件第一次加载时,系统会将音效文件随机分配一个soundID,可以在下次播放时直接使用soundID播放,而无需再次获取对应的url地址
AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(url), &soundID);
//属性记录
self.soundid = soundID;
//2. 播放音效(音效: 不超过30s的短音乐)
///播放音效有两种类型,一种是带振动(必须要真机),一种不带振动
if (alert) {
//带振动
AudioServicesPlayAlertSound(soundID);
}else {
//不带振动
AudioServicesPlaySystemSound(soundID);
}
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//带振动
AudioServicesPlayAlertSound(self.soundid);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end

浙公网安备 33010602011771号