音效格式 | 硬件解码 | 软件解码 |
---|---|---|
*AAC | YES | YES |
ALAC | YES | YES |
HE-AAC | YES | |
iLBC | YES | |
*IMA4 | YES | |
LimeaPCM | YES | |
MP3 | YES | YES |
*CAF | YES | YES |
还有一个带阿拉伯数字的格式,我不会打,就算了,反正他支持硬件解码,不支持软件解码
直接上代码
ZGAudioTool.h
#import "ZGAudioTool.h"
#import <AVFoundation/AVFoundation.h>
@implementation ZGAudioTool
static NSMutableDictionary *_soundIDs;
/*
+ (void)initialize
{
_soundIDs = [NSMutableDictionary dictionary];
}
*/
+ (NSMutableDictionary *)soundIDs
{
if (!_soundIDs) {
_soundIDs = [NSMutableDictionary dictionary];
}
return _soundIDs;
}
+ (void)playAudioWithFilename:(NSString *)filename
{
/*
// -1.创建URL
NSURL *url = [[NSBundle mainBundle] URLForResource:filename withExtension:nil];
// 0.创建音效ID
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID);
// 1.播放音效(本地音效)
#warning ios8的模拟器不支持播放音效(真机可以)
AudioServicesPlaySystemSound(soundID);
*/
// 0.判断文件名是否为nil
if (filename == nil) {
return;
}
// 1.从字典中取出音效ID
SystemSoundID soundID = [[self soundIDs][filename] unsignedIntValue];
// 判断音效ID是否为nil
if (!soundID) {
NSLog(@"创建新的soundID");
// 音效ID为nil
// 根据文件名称加载音效URL
NSURL *url = [[NSBundle mainBundle] URLForResource:filename withExtension:nil];
// 判断url是否为nil
if (!url) {
return;
}
// 创建音效ID
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID);
// 将音效ID添加到字典中
[self soundIDs][filename] = @(soundID);
}
// 播放音效
AudioServicesPlaySystemSound(soundID);
}
+ (void)disposeAudioWithFilename:(NSString *)filename
{
// 0.判断文件名是否为nil
if (filename == nil) {
return;
}
// 1.从字典中取出音效ID
SystemSoundID soundID = [[self soundIDs][filename] unsignedIntValue];
if (soundID) {
// 2.销毁音效ID
AudioServicesDisposeSystemSoundID(soundID);
// 3.从字典中移除已经销毁的音效ID
[[self soundIDs] removeObjectForKey:filename];
}
}
@end
ViewController.h
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "ZGAudioTool.h"
@interface ViewController ()
@property (nonatomic, assign) SystemSoundID soundID;
@end
@implementation ViewController
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 利用工具类播放音效
[ZGAudioTool playAudioWithFilename:@"buyao.wav"];
// 随机播放
// NSString *filename = [NSString stringWithFormat:@"m_%02d.wav", arc4random_uniform(14) + 3];
// [ZGAudioTool playAudioWithFilename:filename];
// 同一时刻播放多个音效
// [ZGAudioTool playAudioWithFilename:@"m_17.wav"];
// [ZGAudioTool playAudioWithFilename:@"buyao.wav"];
// 利用AudioServicesPlaySystemSound播放音乐, 但是注意: 真实开发中不建议使用该函数播放音乐
[ZGAudioTool playAudioWithFilename:@"normal.aac"];
}
// 接收到内存警告
- (void)didReceiveMemoryWarning
{
[ZGAudioTool disposeAudioWithFilename:@"buyao.wav"];
}
@end