Search code examples
iosswiftswift3avplayerswift4

AvPlayer is unable to play sound in device


My code perfectly works fine in the simulator and it streams the url without any issue. But when plugged to the actual device it doesnt play the audio. My code as bellow

var playerItem: AVPlayerItem?
var player: AVPlayer?

func initPlayer() {
    let url:URL = URL(string:"https://storage.googleapis.com/purelightdatabucket/samples%2F60-Energy%20UPLIFT.mp3")!
    self.playerItem = AVPlayerItem(url: url)
    self.player=AVPlayer(playerItem: self.playerItem!)
    let playerLayer=AVPlayerLayer(player: self.player!)
    playerLayer.frame = CGRect(x: 0, y: 0, width: 10, height: 50) // actually this player layer is not visible
    self.view.layer.addSublayer(playerLayer)
}

Solution

  • Put this code in didFinishLaunchingWithOptions

     do {
           try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
           try AVAudioSession.sharedInstance().setActive(true)
     } catch {
         print(error)
     }