Better way to do skip to previous with AVQueuePlayer?

后端 未结 6 1060
难免孤独
难免孤独 2020-12-28 18:29

I am using an AVQueuePlayer in my app. I have a two swipe gestures to skip to next and skip to previous avplayeritems. Right now to do skip to next I am just ca

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-28 18:48

    It seems like AVQueuePlayer removes the current item from the play queue when calling advanceToNextItem. Theoretically, there is no way to get this item back without rebuilding the queue.

    What you could do is use a standard AVPlayer, have an array of AVPlayerItems, and an integer index which keeps the index of the current track.

    Swift 3:

    let player = AVPlayer()
    let playerItems = [AVPlayerItem]() // your array of items
    var currentTrack = 0
    
    func previousTrack() {
        if currentTrack - 1 < 0 {
            currentTrack = (playerItems.count - 1) < 0 ? 0 : (playerItems.count - 1)
        } else {
            currentTrack -= 1
        }
    
        playTrack()
    }
    
    func nextTrack() {
        if currentTrack + 1 > playerItems.count {
            currentTrack = 0
        } else {
            currentTrack += 1;
        }
    
        playTrack()
    }
    
    func playTrack() {
    
        if playerItems.count > 0 {
            player.replaceCurrentItem(with: playerItems[currentTrack])
            player.play()
        }
    }
    

    Swift 2.x:

    func previousTrack() {
        if currentTrack-- < 0 {
            currentTrack = (playerItems.count - 1) < 0 ? 0 : (playerItems.count - 1)
        } else {
            currentTrack--
        }
    
        playTrack()
    }
    
    func nextTrack() {
        if currentTrack++ > playerItems.count {
            currentTrack = 0
        } else {
            currentTrack++;
        }
    
        playTrack()
    }
    
    func playTrack() {
    
        if playerItems.count > 0 {
            player.replaceCurrentItemWithPlayerItem(playerItems[currentTrack])
            player.play()
        }
    }
    

提交回复
热议问题