I want to allow a player to use their music in my game, so I want to know how to detect if the player is playing music from his music library so I can let his music continue playing and if not let my music play in the background.
I use this code to play music in my GameViewController
:
let bgMusicURL: NSURL = NSBundle.mainBundle().URLForResource("Squart-GameMusic", withExtension: "wav")!
do {
Data.GameMusic = try AVAudioPlayer(contentsOfURL: bgMusicURL, fileTypeHint: nil)
} catch {
return print("no music file")
}
Data.GameMusic.numberOfLoops = 1
Data.GameMusic.prepareToPlay()
Data.GameMusic.play()
The problem is that when I try to play music from Music Library the sound stops and it lets my app play music instead of the Music Library.
Check whether the music is playing or not in the background like this
if MPMusicPlayerController.systemMusicPlayer().playbackState == .Playing {
print("Music is playing")
} else {
print("Play your music")
}
Don't forget to import:
import MediaPlayer
And if you want to play the sound simultaneously then use this code to play the sound file
func playSound {
var soundID: SystemSoundID = 0
let soundURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), "myFileName", "mp3", nil)
AudioServicesCreateSystemSoundID(soundURL, &soundID)
AudioServicesPlaySystemSound(soundID)
}