Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

ios - 'An AVPlayerItem cannot be associated with more than one instance of AVPlayer'

I know this question is all over Stack Overflow but still, most of them are old and not related with what I'm going to ask here.

So I've got an array with AVPlayerItems and an AVQueuePlayer. At first I set the AVQueuePlayer to play the array items:

func mediaPicker(mediaPicker: MPMediaPickerController!, didPickMediaItems mediaItemCollection: MPMediaItemCollection!) {

    mediaItems = mediaItemCollection.items

    for thisItem in mediaItems as [MPMediaItem] {

        var itemUrl = thisItem.valueForProperty(MPMediaItemPropertyAssetURL) as? NSURL
        var playerItem = AVPlayerItem(URL: itemUrl)
        mediaArray.append(playerItem)           

    }

    updateMetadata()

    audioPlayer = AVQueuePlayer(items: mediaArray)


    self.dismissViewControllerAnimated(true, completion: nil)

}

But, when the user, for example, adds a new Item or delete one, I try updating the player (the same way I set it in the first place), but it gives me the error. I want to know if there is any way around of it, or any solution. This is how the user deletes a song:

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == UITableViewCellEditingStyle.Delete{
            mediaArray.removeAtIndex(indexPath.row)
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
            audioPlayer = AVQueuePlayer(items: mediaArray) //here gives the error
        }
    }

I'm killing myself over this, so, if someone can help me, I would appreciate it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is that you're creating a new player object when you update the array of items with this line (in tableView:commitEditingStyle:forRowAtIndexPath:),

audioPlayer = AVQueuePlayer(items: mediaArray)

It seems that the player items are still associated with the original player when you do this. You should be able to delete that line, to make it work properly. Inserting or deleting items from mediaArray should be enough to do what you want; you don't need to create a new player.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...