swift - 代表哪个告诉 Swift AvAudio 中是否播放了其他声音?
问题描述
我正在使用 AVAudioEngine 录制语音以将语音转换为文本,但如果用户手机突然开始播放音乐或铃声,我需要停止录制吗?是否有 AVAudio 代表告诉我何时播放其他音乐?
解决方案
假设您的 AVAudioSession 的类别是playback
(默认类别),那么您可以订阅并接收此类中断的通知:
func setupNotifications() {
let nc = NotificationCenter.default
nc.addObserver(self,
selector: #selector(handleInterruption),
name: AVAudioSession.interruptionNotification,
object: AVAudioSession.sharedInstance)
}
@objc func handleInterruption(notification: Notification) {
guard let userInfo = notification.userInfo,
let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
let type = AVAudioSession.InterruptionType(rawValue: typeValue) else {
return
}
// Switch over the interruption type.
switch type {
case .began:
// An interruption began. Update the UI as necessary.
case .ended:
// An interruption ended. Resume playback, if appropriate.
guard let optionsValue = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt else { return }
let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue)
if options.contains(.shouldResume) {
// An interruption ended. Resume playback.
} else {
// An interruption ended. Don't resume playback.
}
default: ()
}
}
从相关文档。
推荐阅读
- c# - 更改后如何将通知从 mysql 发送到 c# 表单?
- ios - 如何解决此边界问题
- python - 如何将 Flask 中的数据发送到另一个页面?
- javascript - 暂时阻止页面通过 Selenium WebDriver 中的 Ajax / Javascript 刷新?
- android - RecyclerView Pagination 和 ViewPager 共享数据
- matrix - 在 rmarkdown 中写一个分区矩阵
- r - 度量精度不适用于回归模型
- typescript - 如何定义redux thunk函数的mapDispatchToProps类型
- javascript - 如何在不刷新页面的情况下将选择选项设置为默认值
- c - C - 如何修复递归函数返回类型错误