Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 781
zantuja Avatar asked Jul 14 '16 22:07

zantuja


1 Answers

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")
}
like image 180
szym Avatar answered Sep 21 '22 01:09

szym