H Sefein
H Sefein

Reputation: 15

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()
}

Upvotes: 1

Views: 7067

Answers (2)

Tapas Pal
Tapas Pal

Reputation: 7207

You can enable a session also for background playing capability.

func enableBackgroundPlaying(_ enable: Bool) throws {
    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        do {
            try AVAudioSession.sharedInstance().setActive(enable)
        } catch {
            throw error
        }
    } catch {
        throw error
    }
}

Upvotes: 1

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71852

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")

Upvotes: 17

Related Questions