2

Hai i am playing mp3 from live streaming using MPMoviePlayerController but it doesn't play when app is running in background. and it stop playing when the phone is locked. please tell me how can i play live streaming audio both in background and phone is locked. suggest me asap please.

I am using MPMoviePlayerController instead of AvAudioPlayer. because of AvAudioPlayer doesn't support network streaming reference.

NOTE:

language - Swift 2.0

UPDATE 1

Finally coded with AVPlayer. But It doesn't play my audio from url This mp3 need to play in my app. My code is

override func viewDidLoad() {
    audioUrl = NSURL(string: "http://www.raagam.co/4256s5f46ht4he4r6/2016/Achcham%20Enbathu%20Madamaiyada/Thalli%20Pogathey.mp3")!
    let avAsset = AVURLAsset(URL: audioUrl)
    let avPlayerItem = AVPlayerItem(asset: avAsset)

    avPlayer = AVPlayer(playerItem: avPlayerItem)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.playerItemDidReachEnd), name: AVPlayerItemDidPlayToEndTimeNotification, object: avPlayer.currentItem)
    avPlayer.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.New, context: nil)
    super.viewDidLoad()
}

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {

    if (object!.isEqual(avPlayer) && keyPath=="status"){
        print("Observer")
        if avPlayer.status == AVPlayerStatus.ReadyToPlay{
            print("ReadyToPlay")
            avPlayer.play();
        }else if avPlayer.status == AVPlayerStatus.Failed{
            print("Failed")
        }else if avPlayer.status == AVPlayerStatus.Unknown{
            print("Unknown")
        }
    }
}

func playerItemDidReachEnd(){
        print("Finished")
}

I use this code from here

When I run this code. It prints ReadyToPlay. But mp3 is not playing.

Community
  • 1
  • 1
AvisSiva
  • 707
  • 1
  • 9
  • 17

1 Answers1

1

You can do this by enabling background audio in your Project > Capabilities pane:

Capabilities pane in Xcode

then hitting play.

But instead of MPMoviePlayerController or AVAudioPlayer, use AVPlayer.

Rhythmic Fistman
  • 34,352
  • 5
  • 87
  • 159