在我的 iPhone 应用程序中,我使用 AVAudioPlayer 来播放歌曲...但是当我在播放歌曲期间拔出或插入耳机时,它会自动停止 AVAudioPlayer...即使发生这些更改,我也需要运行音频播放器..任何想法将不胜感激。提前致谢。
最佳答案
首先,您必须告诉 AVAudioSession
您的应用的音频行为。 Apple 将其命名为 Audio Session 类别,可以通过以下方式设置
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
例如,AVAudioSessionCategoryPlayback
:
When using this category, your app audio continues with the Silent switch set to silent or when the screen locks. (The switch is called the Ring/Silent switch on iPhone.)
This category normally prevents audio from other apps from mixing with your app's audio. To allow mixing for this category, use the kAudioSessionProperty_OverrideCategoryMixWithOthers property.
然后,一旦 Audio Session 设置,应用程序将响应一些音频通知,例如 AVAudioSessionInterruptionNotification
或 AVAudioSessionRouteChangeNotification
为了回答原来的问题,当音频路由更改时会调用 AVAudioSessionRouteChangeNotification
(例如:耳机插入/插入,而且蓝牙设备关闭,...) 。通过一些代码,我们可以找到路由更改的原因。并且,在我们的例子中,如果耳机已拔出,请重新启动播放器。
- (void)viewDidLoad {
[super viewDidLoad];
NSError *setCategoryErr;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
// Detects when the audio route changes (ex: jack unplugged)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioHardwareRouteChanged:) name:AVAudioSessionRouteChangeNotification object:nil];
// Don't forget to remove notification in dealloc method!!
}
- (void)audioHardwareRouteChanged:(NSNotification *)notification {
NSInteger routeChangeReason = [notification.userInfo[AVAudioSessionRouteChangeReasonKey] integerValue];
if (routeChangeReason == AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {
// if we're here, the player has been stopped, so play again!
[self.player play];
}
}
总而言之,还要考虑一下用户在一次无聊的 session 中不小心拔掉了耳机的情况。他不会有这种会让房间里的设备突然尖叫的行为!
关于iphone - 避免耳机插头在 iOS 中停止 AVAudioPlayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17103148/