shane shane - 10 months ago 75
iOS Question

Swift 3 Game Music Play

I have a single view application with a few view each having their own view controller class. I also have a game game and a game view controller, I was wondering how I could play a game music starting from the start screen view controller and have it continue to play through out all of my views and game scene? So that way I don't have to say play when x-screen is loaded so it doesn't restart every time the player changes views.

Answer Source

You can play the music form your AppDelegate. Put this code in your applicationDidFinishLaunching()

let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3")!
var player: AVAudioPlayer!

do {
    player = try AVAudioPlayer(contentsOf: url)
    guard let player = player else { return }

} catch let error {

This will play the music as soon as your app is launched and continue until told to stop or the app closes.