AVAudioPlayer 本地音频设置第三弹:后台播放音频
设备/引擎:Mac(11.6)/cocos
开发工具:Xcode(13.0)
开发语言:Objective-c/c++
开发需求:满足后台播放音频
前面已经实现过了多个音频的播放及单个音频的音量调节,本篇文章将解决后台播放音频的问题。
1.工程设置
在工程中选择"Signing & Capabilities"->“Background Modes”->勾选第一项,如下图所示,一般工程中有音视频都需要勾选该选项。
2.工程"info"中的"key"值添加
在工程中选择"info"->“Custom IOS Target Properties”->添加"Required background modes"值(本身有的就不用添加),并勾选其中的"App plays audio or streams audio/video",如下图所示,此步骤为让音频可以在后台播放。
3.在需要后台播放的音频的部分添加IOS代码
结合前两弹的内容,我的项目中的代码如下:
void DeviceManager::setAudioVolume(const char* audioName,const char* audioName1,float volume,int audiosIndex){
// AVAudioPlayer* player;
NSString* name =[[NSString alloc] initWithUTF8String:audioName]; //传递音频文件路径名称
NSString* name1 =[[NSString alloc] initWithUTF8String:audioName1]; //传递音频文件类型(mp3/m4a……)
NSString* path = [[NSBundle mainBundle] pathForResource:name ofType:name1]; //音频路径、类型(mp3/m4a……)字符串
NSURL* urlMusic = [NSURL fileURLWithPath:path]; //获取路径、类型
player[audiosIndex] = [[AVAudioPlayer alloc] initWithContentsOfURL:urlMusic error:nil]; //将获取到的路径、类型给到player
[player[audiosIndex] prepareToPlay]; //播放准备
// if(audiosIndex==3){
player[audiosIndex].numberOfLoops = -1; //播放循环 (>0为设置的循环次数,<0为无限循环)
// }else{
// player[audiosIndex].numberOfLoops = 0;
// }
player[audiosIndex].volume = volume; //播放音频音量
// player[audiosIndex].enableRate = YES; //控制音频播放速度
// player[2].rate = 0.8;
[player[audiosIndex] play]; //播放音频(必须添加,负责无法播放)
// [player stop];
[[AVAudioSession sharedInstance] setActive:YES error:nil]; //后台播放设置
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
}
至此音频即可在后台/锁屏状态下播放。
4.问题
当在黑屏状态时,除无限循环的音频其它音频会停止播放,也就是程序被挂起,程序中对音频的操作未被调用,找了很多解决方法都没什么效果……
现在暂时的解决办法:将所有音频均设置为无限循环播放,对于需要中间间隔时间的音频就是通过剪辑完成。问题已解决!!!
大家有什么其它的解决方案,欢迎分享!!!
至此项目中有关AVAudioPlayer的部分基本完成,此章节也告一段落!希望能给大家提供一些参考帮助!!!