我开发了一个iPhone应用程序,允许其他应用程序在后台播放音频。为实现这一目标,我将我的音频会话初始化为:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
在我的应用程序的某个时刻,我提供了一个音频播放器,用AVAudioPlayer播放存储在CoreData中的一些文件。当用户点击播放按钮时,应暂停背景音频。当播放器完成或暂停时,背景音频应恢复播放。
播放器播放完
后重新开始播放-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[[AVAudioSession sharedInstance] setActive:NO withFlags:AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation error:nil];
}
就像一个魅力,暂停后我就被简历困住了。它应该在按钮的IBAction中以相同的方式工作
-(IBAction)pausePlayer
{
if (self.player.isPlaying) {
[self.player pause];
[[AVAudioSession sharedInstance] setActive:NO withFlags:AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation error:nil];
}
}
但我总是得到同样的错误:
Unable to deactivate audio session. Error: Error Domain=NSOSStatusErrorDomain Code=560030580 "The operation couldn’t be completed. (OSStatus error 560030580.)"
为什么在这种情况下无法取消激活AudioSession的任何建议?
答案 0 :(得分:2)
我试了3个小时终于得到了它就是我所做的
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@property(strong, nonatomic)AVAudioPlayer *player;
@property(strong)AVAudioSession *session;
@end
@implementation ViewController
- (IBAction)playsound:(id)sender
{
NSURL *url=[[NSURL alloc]initWithString:[[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]];
NSError *err;
self.player=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:&err];
[self.player setDelegate:self];
[self.player setVolume:2.5];
self.session=[AVAudioSession sharedInstance];
[self.player prepareToPlay];
[self.player play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
NSError *err;
[self.session setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&err];
}
@end
答案 1 :(得分:1)
似乎停用太早了。根据AVAudioSession类引用&#34;如果当前正在运行任何关联的音频对象(例如队列,转换器,播放器或录像机),则取消激活会话将失败。&#34;
似乎有一些解决方案:
在循环中运行停用,直到成功。
推迟停用,例如直到真的有必要。
使用时,例如音频队列服务,您可以考虑立即停止。 (未经测试)
在可以收听录音的录音应用程序中,我只在使用序列更改类别之前停用:激活NO,setCategory并激活YES。
参见例如&#34;当您的应用程序正在运行时,Apple建议您在更改任何设置值之前停用音频会话&#34;在Apple的音频会话编程指南