
IOS
IOS AVAudioPlayer 使其他应用程序的背景音乐停止
在开发 IOS 应用程序时,我们经常会遇到需要播放音乐的需求。然而,如果我们的应用程序同时播放音乐,而用户的设备上又有其他应用程序正在播放背景音乐,这就会导致两个音乐同时播放的问题。为了解决这个问题,我们可以利用 AVAudioPlayer 类提供的功能,使其他应用程序的背景音乐停止。使用 AVAudIOSession 设置音频会话要实现这个功能,首先我们需要获取应用程序的音频会话,并设置其类别为 AVAudIOSessionCategorySoloAmbient。这样做的目的是告诉系统,我们的应用程序将独占音频会话,并停止其他应用程序的背景音乐。Swiftimport AVFoundationfunc setupAudIOSession() { let audIOSession = AVAudIOSession.sharedInstance() do { try audIOSession.setcategory(.soloAmbient) } catch { // 处理错误 }}初始化 AVAudioPlayer 并播放音乐一旦我们设置了音频会话,接下来就可以初始化 AVAudioPlayer 对象并开始播放音乐了。在初始化 AVAudioPlayer 对象时,我们需要传入音乐文件的 URL。Swiftimport AVFoundationfunc playMusic() { guard let url = Bundle.mAIn.url(forResource: "music", withExtension: "mp3") else { return } do { let audioPlayer = try AVAudioPlayer(contentsOf: url) audioPlayer.prepareToPlay() audioPlayer.play() } catch { // 处理错误 }}停止其他应用程序的背景音乐通过上述步骤,我们已经设置了音频会话并开始播放音乐。现在,我们需要在应用程序进入前台时停止其他应用程序的背景音乐,并在应用程序退到后台时恢复它们的音乐。Swiftimport AVFoundationclass ViewController: UIViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(handleAudIOSessionInterruption), name: AVAudIOSession.interruptionNotification, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self, name: AVAudIOSession.interruptionNotification, object: nil) } @objc func handleAudIOSessionInterruption(notification: NSNotification) { guard let userInfo = notification.userInfo, let interruptionTypeValue = userInfo[AVAudIOSessionInterruptionTypeKey] as? UInt, let interruptionType = AVAudIOSession.InterruptionType(rawValue: interruptionTypeValue) else { return } switch interruptionType { case .began: // 应用程序进入前台,停止其他应用程序的背景音乐 AVAudIOSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) case .ended: // 应用程序退到后台,恢复其他应用程序的音乐 AVAudIOSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation) default: break } }}通过上述步骤,我们可以使用 AVAudioPlayer 类使其他应用程序的背景音乐停止。首先,我们需要设置音频会话的类别为 AVAudIOSessionCategorySoloAmbient。然后,我们可以初始化 AVAudioPlayer 对象并开始播放音乐。最后,在应用程序进入前台和退到后台时,我们需要通过监听 AVAudIOSession 的中断通知来停止和恢复其他应用程序的音乐。这样,我们的应用程序就可以在播放音乐的同时,停止其他应用程序的背景音乐,提供更好的用户体验。Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号