* 支持格式 wav caf pcm amr(不支持)
//需要导入#import <AudioToolbox/AudioToolbox.h>
1.获得音效文件的路径
NSURL *url = [[NSBundle mainBundle] URLForResource:@"m_03.wav" withExtension:nil];
2.加载音效文件,得到对应的音效ID
SystemSoundID soundID = 0;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID);
3.播放音效
AudioServicesPlaySystemSound(soundID);
注意:音效文件只需要加载1次
4.音效播放常见方法总结
加载音效文件
AudioServicesCreateSystemSoundID(CFURLRef inFileURL, SystemSoundID *outSystemSoundID)
释放音效资源
AudioServicesDisposeSystemSoundID(SystemSoundID inSystemSoundID)
播放音效
AudioServicesPlaySystemSound(SystemSoundID inSystemSoundID)
播放音效带点震动
AudioServicesPlayAlertSound(SystemSoundID inSystemSoundID)
下面来看一下实例:
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@end
@implementation ViewController
SystemSoundID soundID = 0;
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"msgcome.wav" withExtension:nil];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
AudioServicesPlaySystemSound(soundID);
}
- (void)dealloc
{
//释放音效资源
AudioServicesDisposeSystemSoundID(soundID);
}