I have a play button and when it is clicked it will play the song in parse. The program finds the song and gets the link, I checked in debug mode, but for some reason it's not playing the song. I played a song in the native music app, and when I click the play button in the app it stops the music playing in the background. I don't think it's a programming bug. Why is it not working?
func playit(sender: UIButton!){
let cell: UITableViewCell = self.table.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
let playButtonrow = sender.tag
println(titleatcell[playButtonrow])
if let nowPlaying = musicPlayer.nowPlayingItem{
let title = nowPlaying[MPMediaItemPropertyTitle] as? String
let artist = nowPlaying[MPMediaItemPropertyTitle] as? String
println("now playing \(title!) \(artist!)")
println("cell: \(playButtonrow) \(titleatcell[playButtonrow])")
let query = PFQuery(className: "Songs")
query.whereKey("SongName", equalTo: titleatcell[playButtonrow])
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
println("Successfully retrieved \(objects!.count) song(s).")
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
println(object.objectId)
println(playButtonrow)
let object = object as PFObject
let parseAudio = object.valueForKey("SongFile") as! PFFile
let audioPath: String = parseAudio.url!
let urlParse: NSURL = NSURL(string: audioPath)!
player = AVPlayer(URL: urlParse)
println(player)
player.volume = 1.0
player.play()
if (player.rate > 0) && (player.error == nil) {
// player is playing
println("Playing")
} else {
println("Not Playing")
}
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
}
}
You need to put the AVPlayer
code on the main thread. Wrap the code in dispatch_async
:
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
println("Successfully retrieved \(objects!.count) song(s).")
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
println(object.objectId)
println(playButtonrow)
let object = object as PFObject
let parseAudio = object.valueForKey("SongFile") as! PFFile
let audioPath: String = parseAudio.url!
let urlParse: NSURL = NSURL(string: audioPath)!
dispatch_async(dispatch_get_main_queue(), { () -> Void in
player = AVPlayer(URL: urlParse)
println(player)
player.volume = 1.0
player.play()
if (player.rate > 0) && (player.error == nil) {
// player is playing
println("Playing")
} else {
println("Not Playing")
}
})
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.