mardi 27 janvier 2015

Swift. Unable to play next song in background mode with AVPlayer

I have already added "App plays audio or streams audio/video using AirPlay" and "App downloads content from the network" lines to "Required Background Modes" in Info.plist. The following code plays fine one song in background. But when it's trying to load new song after current song is finished playing, it successfully goes to "self.player.play()" line which is in "play" function which is calling from "playerDidFinishPlaying" function, and does nothing. I think that app may need more permission for more memory allocation or something like this.



func playerDidFinishPlaying(note: NSNotification){
println("finished")
curr_row = (curr_row + 1) % songs.count
play()
}


func play(){
let song = songs[curr_row]
self.label1.text = song.title + " - " + song.author
self.Download_toggle(self.g.playlist_containts(song.id) ? 2:1)
self.imageView.image = nil
self.label_currentTime.text = self.timeToString(0)
self.label_duration.text = ""
self.PlayPause_toggle(2)
self.progressView.setProgress(0, animated: false)

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
//player
if (self.player != nil) {
self.player = nil
}
var steamingURL:NSURL!
if (self.g.r_mode() == 1) {
steamingURL = NSURL(string:self.g.r_url_prefix()+"mp3/"+song.id+".mp3")
} else {
let filePath = self.g.r_dir()+"mp3/"+song.id+".mp3"
steamingURL = NSURL(fileURLWithPath: filePath)
}
self.item = AVPlayerItem(URL: steamingURL)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: self.item)
self.player = AVPlayer(playerItem: self.item)
self.player.play()
//endOf player

//img
var imageData:NSData!
if (self.g.r_mode() == 1) {
let url:NSURL! = NSURL(string:self.g.r_url_prefix()+"images2/"+song.id+".jpg")!
imageData = NSData(contentsOfURL: url, options: nil, error: nil)
} else {
imageData = NSData(contentsOfFile: self.g.r_dir()+"images2/"+song.id+".jpg") //filePath
}
dispatch_async(dispatch_get_main_queue(), {
if (imageData != nil) {
self.imageView.image = UIImage(data:imageData)
}
})
//endOf img
})
}


App works perfect in "Active" mode. I would really appreciate any help to solve this problem.


Aucun commentaire:

Enregistrer un commentaire