Search code examples
swiftavplayer

Play a pls file with AVPlayer?


I've the code shown below. It looks pretty simple. But it is not playing any audio. How am I need to modify this func

import AVFoundation
import MediaPlayer
    

func play(){
    let player = AVPlayer(URL: NSURL(string: "http://somewebpage.com/abc.pls")!)
    player.play()
}

Solution

  • The problem is that player is a local variable. It exists for two lines of play() and vanishes in a puff of smoke. So before it has a chance to play anything, it has vanished. You asked it to play and then you immediately killed it! Not very nice. It wanted to do your bidding but you never gave it a chance...

    Simply promote it to be an instance variable of whatever class this is:

    var player : AVPlayer!
    func play(){
        self.player = AVPlayer(URL: NSURL(string: "http://somewebpage.com/abc.pls")!)
        self.player.play()
    }