【发布时间】:2018-02-22 11:32:00
【问题描述】:
苹果表示,当耳机拔出时,iOS会自动停止播放。
虽然在使用 AVPlayer 时确实如此,但在使用 AVAudioPlayer 时实际上并没有按预期工作,而是继续从内置扬声器播放音频。 p>
【问题讨论】:
标签: ios swift avplayer avaudioplayer
苹果表示,当耳机拔出时,iOS会自动停止播放。
虽然在使用 AVPlayer 时确实如此,但在使用 AVAudioPlayer 时实际上并没有按预期工作,而是继续从内置扬声器播放音频。 p>
【问题讨论】:
标签: ios swift avplayer avaudioplayer
我不确定,但试试这个:
- (void)viewDidLoad {
[super viewDidLoad];
NSError *setCategoryErr;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
// Detects when the audio route changes (ex: headphones 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 old device is unavailable == headphones have been unplugged, so stop manually!
[self.player stop];
}
}
【讨论】:
你需要观察硬件路由变化观察器并基于回调,你可以停止播放。
设置您的播放器 - 播放音频(即使在静音模式下)并使其他音乐静音:
let audioSession = AVAudioSession.sharedInstance()
_ = try? audioSession.setCategory(AVAudioSessionCategoryPlayback, with: .duckOthers)
_ = try? audioSession.setActive(true)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(audioRouteChanged), name: .AVAudioSessionRouteChange, object: nil)
func audioRouteChanged(note: Notification) {
if let userInfo = note.userInfo {
if let reason = userInfo[AVAudioSessionRouteChangeReasonKey] as? Int {
if reason == AVAudioSessionRouteChangeReason.oldDeviceUnavailable.hashValue {
// headphones plugged out
player.stop()
}
}
}
}
重要提示:如果路由更改原因是 AVAudioSessionRouteChangeReasonOldDeviceUnavailable,媒体播放应用应该暂停播放,但如果原因是 AVAudioSessionRouteChangeReasonOverride,则不应暂停播放。
【讨论】:
重要提示:如果路由更改原因是
AVAudioSessionRouteChangeReasonOldDeviceUnavailable,媒体播放应用应该暂停播放,但如果原因是AVAudioSessionRouteChangeReasonOverride,则不应。
“应该”可以表示职责或事件发生的可能性。 在这种情况下,这意味着您有责任在耳机等被拔出时实施暂停,并且不会在您没有任何干预的情况下可能会发生这种情况(因为您'见过,它没有)。
以新鲜的眼光看待它,文档模棱两可。应该不是一个好的词选择。
【讨论】: