Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVPlayer stops on background

I am using AVPlayer to play audio from an URL. Everything works as expected until the APP goes on background or the iphone enter in sleep mode.

How can I prevent this from happening.

I've added to the info.plist:

enter image description here

Here is my code.

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let playTrackID = tracks[indexPath.row].trackID

    let urlString = url
    let url = NSURL(string: urlString)!

    avPlayer = AVPlayer(URL:url)

    avPlayer.play()

}

Any idea?

UPDATE: SOLVED by @Danil Gontovnik

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let playTrackID = tracks[indexPath.row].trackID

    let urlString = url
    let url = NSURL(string: urlString)!

    do {

        avPlayer = AVPlayer(URL:url)

        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)

    }

    catch {

        print("Something bad happened. Try catching specific errors to narrow things down")
    }


    avPlayer.play()
like image 430
user3163404 Avatar asked Aug 24 '15 15:08

user3163404


1 Answers

I think that you forgot to set your AVAudioSession to be active. Try to add this code:

var categoryError: NSError?
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: &categoryError)

if categoryError != nil {
    // Handle error
}

var activeError: NSError?;
AVAudioSession.sharedInstance().setActive(true, error: &activeError)

if activeError != nil {
    // Handle error
}

More information on AVAudioSession can be found here.

like image 59
gontovnik Avatar answered Oct 14 '22 13:10

gontovnik