音频播放,后台播放,锁频控制

这篇博客主要介绍了在iOS平台上实现短音频和长音频的播放,包括使用C语言方法和AVFoundation库。还讨论了音频播放器的控制,如播放、暂停、停止,并解释了prepareToPlay和stop方法的区别。此外,提到了后台播放设置和音频中断的处理方法。最后,简述了录音功能的实现步骤。
摘要由CSDN通过智能技术生成

我的博客:http://blog.csdn.net/nsydianzi


1.短音频


C语言方法:导入AudioToolbox/AudioToolbox.h

思路步骤:

第一步:获取音频文件的url,并且定义一个音频ID(SystemSoundID由系统自动提供)

第二步:加载对应的音频文件到内存,并对应上音频ID

第三步:播放音频

 
 
 
  1. //音频文件的URL

  2. NSURL *soundUrl = [[NSBundle mainBundle] URLForResource:@"/plane.bundle/enemy1_down.mp3" withExtension:nil];

  3. //音频ID,一个音频文件对应一个soundID

  4. SystemSoundID soundId;

  5. NSLog(@"%d",soundId);

  6. //加载了音频文件到内存

  7. AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundUrl, &soundId);

  8. //播放音频

  9. AudioServicesPlaySystemSound(soundId);


可以抽取一个播放类,用来播放音乐,这个类最好是一个单例,不然音频文件加载太多次,会有内存问题

 
 
 
  1. +(void)initialize{    //加载这个类时,自动将短音频加载进内存

  2.    //1.加载所有音频文件

  3.    //1.1 遍历plane.bundle的所有音频文件

  4.    NSFileManager *manager = [NSFileManager defaultManager];

  5.    

  6.    //1.2获取plane.bundle的路径

  7.    NSString *planePath = [[NSBundle mainBundle] pathForResource:@"plane.bundle" ofType:nil];

  8.    

  9.    NSError *error = nil;

  10.    NSArray *contents = [manager contentsOfDirectoryAtPath:planePath error:&error];

  11.    NSLog(@"%@",contents);

  12.    

  13.    //1.3 遍历里面的mp3文件,创建SystemSoundID

  14.    NSMutableDictionary *soundDictM = [NSMutableDictionary dictionary];

  15.    for (NSString *mp3Name in contents) {

  16.        //音频文件的URL

  17.        NSString *soundUrlStr = [planePath stringByAppendingPathComponent:mp3Name];

  18.        NSURL *soundUrl = [NSURL fileURLWithPath:soundUrlStr];

  19.        

  20.        //音频ID,一个音频文件对应一个soundID

  21.        SystemSoundID soundId;

  22.        

  23.        AudioServicesCreateSystemSoundID((__bridge CFURLRef)(soundUrl), &soundId);

  24.        

  25.        //1.4通过字典存储soundID @{"enemy1_down.mp3":11111,"enemy2_down.mp3",11112}

  26.        soundDictM[mp3Name] = @(soundId);

  27.        

  28.    }

  29.    

  30.    NSLog(@"%@",soundDictM);

  31.    soundDict = soundDictM;

  32. }

 
 
 
  1. //2.给一个方法播放音频文件

  2. -(void)playMp3WithName:(NSString *)mp3Name{    //调用这个公开的方法播放音乐

  3.    //通过键值获取soundId

  4.    SystemSoundID soundId =  [soundDict[mp3Name] unsignedIntValue];

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值