简体   繁体   中英

Swift - Detect music playing, whether it's Spotify or iTunes

I am currently using the following statement to detect music:

if MPMusicPlayerController.systemMusicPlayer().playbackState == .Playing {
    print("There is music playing")
}

Great, however this will only work for iTunes player, and not music that might be coming from a different app, specifically talking about Spotify .

I don't need to know the song being played, simply whether there is anything playing at all, so I can decide whether I provide my own background music for my game or not.

Edit: ideally the solution should cover any 3rd party music program, not just Spotify.

Given iOS: How do I detect if music is playing in any background music app?

the Swift version would be:

let isOtherAudioPlaying = AVAudioSession.sharedInstance().isOtherAudioPlaying()

However, the developer docs suggest that starting with iOS 8.0 you should use secondaryAudioShouldBeSilencedHint instead:

if (AVAudioSession.sharedInstance().secondaryAudioShouldBeSilencedHint()) {
   print("another application with a non-mixable audio session is playing audio")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM