播放外部音频时暂停 AVAudioPlayer
Pause AVAudioPlayer when external audio is playing
我目前遇到了一个问题,如果你们中的一些人遇到了这个问题并提出了一个简单的解决方案,我会很高兴。
所以基本上,问题是:
有什么方法可以让我在收到一些外部声音时暂停正在进行的 AVAudioPlayer,例如:音乐、来电、通知等
我知道为了检测呼叫,有这个新的 CXCallObserverDelegate 可以帮助我们,但是对于音乐和其他方面,是否有任何简单的解决方案来解决所有这些问题?
在代码方面,一切正常,播放音频没有任何问题。我有一个自定义路径和一个错误,错误 returns nil.
NSError *avPlayerError = nil;
NSData* mp3Data = [[NSData alloc] initWithContentsOfFile: path options: NSDataReadingMappedIfSafe error: &avPlayerError];
我正在为我的应用程序使用此代码:
在 AppDelegate 中,didFinishLaunchingWithOptions
为任何传入中断添加观察者
NotificationCenter.default.addObserver(self, selector: #selector(self.onAudioSessionEvent(noti:)), name: Notification.Name.AVAudioSessionInterruption, object: nil)
当任何中断发生时,该函数将被调用
@objc func onAudioSessionEvent(noti:Notification){
if noti.name == Notification.Name.AVAudioSessionInterruption
{
if let value = noti.userInfo![AVAudioSessionInterruptionTypeKey] as? NSNumber {
if value.uintValue == AVAudioSessionInterruptionType.began.rawValue {
print("start interrupt")
}else{
print("end interrupt")
}
}
}
}
我目前遇到了一个问题,如果你们中的一些人遇到了这个问题并提出了一个简单的解决方案,我会很高兴。
所以基本上,问题是: 有什么方法可以让我在收到一些外部声音时暂停正在进行的 AVAudioPlayer,例如:音乐、来电、通知等
我知道为了检测呼叫,有这个新的 CXCallObserverDelegate 可以帮助我们,但是对于音乐和其他方面,是否有任何简单的解决方案来解决所有这些问题?
在代码方面,一切正常,播放音频没有任何问题。我有一个自定义路径和一个错误,错误 returns nil.
NSError *avPlayerError = nil;
NSData* mp3Data = [[NSData alloc] initWithContentsOfFile: path options: NSDataReadingMappedIfSafe error: &avPlayerError];
我正在为我的应用程序使用此代码:
在 AppDelegate 中,didFinishLaunchingWithOptions
为任何传入中断添加观察者
NotificationCenter.default.addObserver(self, selector: #selector(self.onAudioSessionEvent(noti:)), name: Notification.Name.AVAudioSessionInterruption, object: nil)
当任何中断发生时,该函数将被调用
@objc func onAudioSessionEvent(noti:Notification){
if noti.name == Notification.Name.AVAudioSessionInterruption
{
if let value = noti.userInfo![AVAudioSessionInterruptionTypeKey] as? NSNumber {
if value.uintValue == AVAudioSessionInterruptionType.began.rawValue {
print("start interrupt")
}else{
print("end interrupt")
}
}
}
}