H Sefein H Sefein - 7 months ago 19
Swift Question

How to play background music with swift 2.0?

HI I am new to swift and ios development. My code was working up until I've updated to Swift 2.0, I've used swift migrating tool, but I still can't figure out how to sort and fix my code. Please help!

import AVFoundation

var backgroundMusicP: AVAudioPlayer!

func playBackgroundMusic(filename: String) {
let url = NSBundle.mainBundle().URLForResource(
filename, withExtension: nil)
if (url == nil) {
print("Could not find file: \(filename)")
return
}

var error: NSError?

do {

backgroundMusicP = try AVAudioPlayer(contentsOfURL: url!)
} catch {

backgroundMusicP == nil
}
if backgroundMusicP == nil {
print("Could not create audio player: \(error)")
return
}

backgroundMusicP.numberOfLoops = -1
backgroundMusicP.prepareToPlay()
backgroundMusicP.play()
}

Answer

Updated function for swift 2.0:

import AVFoundation

var backgroundMusicPlayer = AVAudioPlayer()

func playBackgroundMusic(filename: String) {
    let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
    guard let newURL = url else {
        print("Could not find file: \(filename)")
        return
    }
    do {
        backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newURL)
        backgroundMusicPlayer.numberOfLoops = -1
        backgroundMusicPlayer.prepareToPlay()
        backgroundMusicPlayer.play()
    } catch let error as NSError {
        print(error.description)
    }
}

Use it this way:

playBackgroundMusic("yourFileName.mp3")