ios - 当 Apple Music/Spotify 在后台播放时暂停的 Swift 背景音乐

标签 ios swift audio sprite-kit xcode8

我希望我的背景歌曲在另一个应用程序的音乐正在播放时停止播放。例如苹果音乐或 Spotify。如果您下载了 color switch,您就会明白我的意思。目前我正在使用下面的方法,但我的背景歌曲并没有阻止它与正在播放的音乐混合。(这种方法有点适用于苹果音乐,但不适用于 Spotify)。我希望我的歌曲无限期地播放,直到其他音乐在背景中播放,并在其他音乐暂停时再次播放。(尝试使用颜色切换)

谢谢

 func setUpAudio() {
        //dead = SKAction.playSoundFileNamed(SoundFile.dead, waitForCompletion: true)
       // buttonpress = SKAction.playSoundFileNamed(SoundFile.button, waitForCompletion: true)

        if GameScene.backgroundMusicPlayer == nil {
            let backgroundMusicURL = Bundle.main.url(forResource: SoundFile.BackgroundMusic, withExtension: nil)

            do {
                let theme = try AVAudioPlayer(contentsOf: backgroundMusicURL!)
                GameScene.backgroundMusicPlayer = theme

            } catch {
                // couldn't load file :[
            }

            GameScene.backgroundMusicPlayer.numberOfLoops = -1
        }

        if !GameScene.backgroundMusicPlayer.isPlaying {
            GameScene.backgroundMusicPlayer.play()
        }
        let audioSession = AVAudioSession.sharedInstance()

        /*try!audioSession.setCategory(AVAudioSessionCategoryAmbient, with: AVAudioSessionCategoryOptions.mixWithOthers
        )*/

        do { try!audioSession.setCategory(AVAudioSessionCategoryAmbient)
        try AVAudioSession.sharedInstance().setActive(true) }
        catch let error as NSError { print(error) }
        //s audio from other sessions to be ducked (reduced in volume) while audio from this session plays
    }

最佳答案

你的 session 类别允许混合,这不是你想要的。尝试使用 AVAudioSessionCategoryPlaybackAVAudioSessionCategorySoloAmbient,因为它们不允许您的应用与其他应用混合音频。

See the docs for more info

关于ios - 当 Apple Music/Spotify 在后台播放时暂停的 Swift 背景音乐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44737442/

相关文章:

ios - 在 UITabBarController 上的导航栏中添加按钮并从 View Controller 调用 Segue

ios - 旧 iOS 设备的蓝牙框架

ios - 在 UITableView 上插入新节或删除节时如何更新 UITableViewDataSource?

ios - UITableViewCells 初始加载 View /显示问题

ios - 表达式类型不明确,没有更多上下文(枚举)

swift - 将 ScrollView/Keyboard 移动到 UITextView 光标位置

ios - 如何在 SwiftUI 和 iOS 14 中更改单元格背景颜色?

c# - 在 Windows 中使用 C# 配置扬声器设置有哪些 API?

ios - iPhone - 如何将 .caf 音频文件转换为 .aac?

audio - 使用什么 ffmpeg 命令将无符号整数列表转换为音频文件?