我的博客:http://blog.csdn.net/nsydianzi
1.短音频
C语言方法:导入AudioToolbox/AudioToolbox.h库
思路步骤:
第一步:获取音频文件的url,并且定义一个音频ID(SystemSoundID由系统自动提供)
第二步:加载对应的音频文件到内存,并对应上音频ID
第三步:播放音频
//音频文件的URL
NSURL *soundUrl = [[NSBundle mainBundle] URLForResource:@"/plane.bundle/enemy1_down.mp3" withExtension:nil];
//音频ID,一个音频文件对应一个soundID
SystemSoundID soundId;
NSLog(@"%d",soundId);
//加载了音频文件到内存
AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundUrl, &soundId);
//播放音频
AudioServicesPlaySystemSound(soundId);
可以抽取一个播放类,用来播放音乐,这个类最好是一个单例,不然音频文件加载太多次,会有内存问题
+(void)initialize{ //加载这个类时,自动将短音频加载进内存
//1.加载所有音频文件
//1.1 遍历plane.bundle的所有音频文件
NSFileManager *manager = [NSFileManager defaultManager];
//1.2获取plane.bundle的路径
NSString *planePath = [[NSBundle mainBundle] pathForResource:@"plane.bundle" ofType:nil];
NSError *error = nil;
NSArray *contents = [manager contentsOfDirectoryAtPath:planePath error:&error];
NSLog(@"%@",contents);
//1.3 遍历里面的mp3文件,创建SystemSoundID
NSMutableDictionary *soundDictM = [NSMutableDictionary dictionary];
for (NSString *mp3Name in contents) {
//音频文件的URL
NSString *soundUrlStr = [planePath stringByAppendingPathComponent:mp3Name];
NSURL *soundUrl = [NSURL fileURLWithPath:soundUrlStr];
//音频ID,一个音频文件对应一个soundID
SystemSoundID soundId;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(soundUrl), &soundId);
//1.4通过字典存储soundID @{"enemy1_down.mp3":11111,"enemy2_down.mp3",11112}
soundDictM[mp3Name] = @(soundId);
}
NSLog(@"%@",soundDictM);
soundDict = soundDictM;
}
//2.给一个方法播放音频文件
-(void)playMp3WithName:(NSString *)mp3Name{ //调用这个公开的方法播放音乐
//通过键值获取soundId
SystemSoundID soundId = [soundDict[mp3Name] unsignedIntValue];