簡體   English   中英

在 Swift 應用程序中斷開音頻設備時如何停止音頻播放?

[英]How to stop audio playback when disconnecting audio devices in Swift app?

我正在編寫一個 Swift 應用程序,它從 Web Radio URL 流式傳輸音頻,但我無法使其在音頻路由更改時正常運行,尤其是在斷開音頻設備連接時。

我參考了 Apple 文檔的這一頁,但是我對示例中如何使用headphonesConnected變量以及如何不僅涵蓋耳機,還涵蓋其他設備(如藍牙耳機、CarPlay 設備等)感到困惑。

基本上我需要我的應用程序通過在外部音頻設備(耳機、BT 耳機、CarPlay 設備)斷開連接時停止播放來遵循 iOS 指南。

先做一個觀察者:

NotificationCenter.default.addObserver(self, selector: #selector(handleRouteChange(_:)), name: AVAudioSession.routeChangeNotification, object: nil)

並實施 handleRouteChange:

 @objc func handleRouteChange(_ notification: Notification) {
          
         //bron: https://developer.apple.com/library/archive/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/HandlingAudioHardwareRouteChanges/HandlingAudioHardwareRouteChanges.html#//apple_ref/doc/uid/TP40007875-CH5-SW3
        
          guard let userInfo = notification.userInfo,
          let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
          let reason = AVAudioSession.RouteChangeReason(rawValue:reasonValue) else {return}
        
          switch reason {
            
          case .routeConfigurationChange:
          
               let session = AVAudioSession.sharedInstance()
          
               for output in session.currentRoute.outputs where output.portType == AVAudioSession.Port.headphones {
            
                    play()
            
                    break
               
               }
            
               for output in session.currentRoute.outputs where output.portType == AVAudioSession.Port.airPlay {

                    play()

                    break

               }

               for output in session.currentRoute.outputs where output.portType == AVAudioSession.Port.carAudio {

                    if isPlaying && autoplayCaraudio {
                         
                         play()

                    }

                    break

               }

          case .oldDeviceUnavailable:
            
               if let previousRoute = userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription {

                    for output in previousRoute.outputs where output.portType == AVAudioSession.Port.headphones {

                         pause()

                         break

                    }

                    for output in previousRoute.outputs where output.portType == AVAudioSession.Port.airPlay {

                         pause()

                         break

                    }

                    for output in previousRoute.outputs where output.portType == AVAudioSession.Port.carAudio {

                         pause()

                         break

                    }

               }
            
          default: ()
            
        }
        
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM