[英]Swift background music that pauses when apple music/ spotify is playing in background
我希望在播放来自另一个应用程序的音乐时停止播放背景音乐。 例如苹果音乐或Spotify。 如果您下载颜色开关,您将会明白我的意思。 目前,我正在使用以下方法,但我的背景歌曲并未停止它与正在播放的音乐混合(此方法有点适用于苹果音乐,但不适用于Spotify)。 我希望我的歌曲可以无限期播放,直到其他音乐在后台播放,并且在其他音乐暂停时重新播放。(尝试使用Color Switch)
谢谢
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
}
您的会话类别允许混合,这不是您想要的。 尝试使用AVAudioSessionCategoryPlayback
或AVAudioSessionCategorySoloAmbient
,因为这些将不允许您的应用程序将音频与其他应用程序混合。
您需要将AVAudioSession设置为active。
let _ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
let _ = try? AVAudioSession.sharedInstance().setActive(true)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.