Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scrub audio with AVPlayer?

I'm using seekToTime for an AVPlayer. It works fine, however, I'd like to be able to hear audio as I scrub through the video, much like how Final Cut or other video editors work. Just looking for ideas or if I've missed something obvious.

like image 322
akaru Avatar asked Mar 28 '14 06:03

akaru


1 Answers

The way to do this is to scrub a simultaneous AVplayer asynchronously alongside the video. I did it this way (in Swift 4):

// create the simultaneous player and feed it the same URL:
    let videoPlayer2 = AVPlayer(url: sameUrlAsVideoPlayer!)
    videoPlayer2.volume = 5.0

//set the simultaneous player at exactly the same point as the video player.
     videoPlayer2.seek(to: sameSeekTimeAsVideoPlayer)

// create a variable(letsScrub)that allows you to activate the audio scrubber when the video is being scrubbed:
    var letsScrub: Bool?
//when you are scrubbing the video you will set letsScrub to true:
    if letsScrub == true {audioScrub()}

//create this function to scrub audio asynchronously:
    func audioScrub() {
        DispatchQueue.main.async {

//set the variable to false so the scrubbing does not get interrupted:
        self.letsScrub = false

//play the simultaneous player
        self.videoPlayer2.play()

//make sure that it plays for at least 0.25 of a second before it stops to get that scrubbing effect:
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {

//now that 1/4 of a second has passed (you can make it longer or shorter as you please) - pause the simultaneous player
            self.videoPlayer2.pause()

//now move the simultaneous player to the same point as the original videoplayer:
            self.videoPlayer2.seek(to: self.sameSeekTimeAsVideoPlayer)

//setting this variable back to true allows the process to be repeated as long as video is being scrubbed:
            self.letsScrub = true
        }
}
}
like image 69
Donovan Marsh Avatar answered Oct 16 '22 17:10

Donovan Marsh