AVPlayer : Play, Pause, Seek, and Time Control in iOS with Swift

AVPlayer : Play, Pause, Seek, and Time Control in iOS with Swift
July 9, 2023 No Comments Development,iOS Development Pushpendra Kumar

AVPlayer is a powerful framework in iOS that allows us to handle video playback with ease. In this blog post, we’ll explore how to implement essential control functionalities for AVPlayer, including play, pause, seek, and time control. By the end of this tutorial, you’ll have a comprehensive understanding of AVPlayer control implementation in iOS using Swift.

Setting up AVPlayer

To get started, we need to set up AVPlayer in our iOS project. First, import the AVFoundation framework:

import AVFoundation

Next, create an instance of AVPlayer and specify the URL of the video you want to play:

private var player : AVPlayer? = nil
private var playerLayer : AVPlayerLayer? = nil
    
    private func setVideoPlayer() {
        guard let url = URL(string: videoURL) else { return }
        
        if self.player == nil {
            self.player = AVPlayer(url: url)
            self.playerLayer = AVPlayerLayer(player: self.player)
            self.playerLayer?.videoGravity = .resizeAspectFill
            self.playerLayer?.frame = self.videoPlayer.bounds
            self.playerLayer?.addSublayer(self.viewControll.layer)
            if let playerLayer = self.playerLayer {
                self.view.layer.addSublayer(playerLayer)
            }
            self.player?.play()
        }
        self.setObserverToPlayer()
    }

The above code we have used for setting up the player with the very easy steps. Here "self.playerLayer?.addSublayer(self.viewControll.layer)" lines plays an important role for controlling elements. I will request you, Please watch the video for understanding more about this.

Play and Pause Functionality

In a customized video player, play and pause functionalities play a crucial role. As a developer, it’s essential to be prepared and skilled in implementing these functionalities based on different client or superior requirements. This tutorial not only guides you in creating a robust video player but also helps you enhance your skillset for handling customized video player features effectively. In this article, we will explore the code implementation for the play and pause functionalities.

@objc private func onTapPlayPause() {
        if self.player?.timeControlStatus == .playing {
            self.imgPlay.image = UIImage(systemName: "pause.circle")
            self.player?.pause()
        } else {
            self.imgPlay.image = UIImage(systemName: "play.circle")
            self.player?.play()
        }
}

The above function will help you manage the video player state. Here self.player?.timeControlStatus will help you understand the current state of the player. So when you are working on it, Make sure to be aware or get information of the timeControlStatus keyword.

Seeking Forward and Backward

In Addition, Seeking Forward and Backward is a convenient feature that allows users to navigate through the content with ease. By simply dragging the seek bar or using the dedicated forward and backward buttons, users can quickly jump to their desired moments in the video or audio playback. This feature enhances the viewing and listening experience, making it effortless to skip to specific scenes, replay favorite parts, or catch up from where they left off. Enjoy seamless control over your media with the Seeking Forward and Backward functionality.

    @objc private func onTap10SecNext() {
        guard let currentTime = self.player?.currentTime() else { return }
        let seekTime10Sec = CMTimeGetSeconds(currentTime).advanced(by: 10)
        let seekTime = CMTime(value: CMTimeValue(seekTime10Sec), timescale: 1)
        self.player?.seek(to: seekTime, completionHandler: { completed in
            
        })
    }
    
    @objc private func onTap10SecBack() {
        guard let currentTime = self.player?.currentTime() else { return }
        let seekTime10Sec = CMTimeGetSeconds(currentTime).advanced(by: -10)
        let seekTime = CMTime(value: CMTimeValue(seekTime10Sec), timescale: 1)
        self.player?.seek(to: seekTime, completionHandler: { completed in
            
        })
    }

Seek avplayer on a particular position or time

Seeking is a useful feature that allows users to navigate to a specific position or time in a video player. With the seek functionality, you can easily skip forward or backward to a desired moment in the video. Whether you want to quickly jump to a particular scene, replay a specific segment, or resume watching from where you left off, seeking enables precise control over your video playback. Simply drag the seek bar or input the desired time in the player interface to instantly navigate to your desired position. Enjoy a seamless viewing experience with the seek feature in the video player. In addition, I am providing the code below!

private var isThumbSeek : Bool = false
    @objc private func onTapToSlide() {
        self.isThumbSeek = true
        guard let duration = self.player?.currentItem?.duration else { return     }
        let value = Float64(self.seekSlider.value) * CMTimeGetSeconds(duration)
        if value.isNaN == false {
            let seekTime = CMTime(value: CMTimeValue(value), timescale: 1)
            self.player?.seek(to: seekTime, completionHandler: { completed in
                if completed {
                    self.isThumbSeek = false
                }
            })
        }
}

As a Result, Above code plays and important role into the video player. It helps you to seek the video player on the particular position. So, You can optimise this in better way as per your requirement.

Update SeekBar when AvPlayer playing the video

Importantly, Updating the SeekBar when using the AVPlayer to play a video refers to the continuous synchronization of the SeekBar position with the progress of the video playback. The SeekBar visually represents the current position or progress of the video. And allowing users to visualize and navigate through the content.

When the AVPlayer is actively playing the video, the SeekBar should reflect the current playback time of the video. As the video progresses, the SeekBar should dynamically update to reflect the elapsed time. And visually indicating the progress of the playback. This ensures that users have an accurate representation of the current position in the video. And  In other words can easily seek to different parts by interacting with the SeekBar.

Moreover, Updating the SeekBar in real-time while the AVPlayer is playing the video enhances the user experience, providing visual feedback and precise control over the playback position. It allows users to easily navigate to specific points in the video and provides a seamless and interactive playback experience.

In addition, I am providing the Code for this, Which can help you for the better programming and enhancing your skills.

    private func updatePlayerTime() {
        guard let currentTime = self.player?.currentTime() else { return }
        guard let duration = self.player?.currentItem?.duration else { return }
        
        let currentTimeInSecond = CMTimeGetSeconds(currentTime)
        let durationTimeInSecond = CMTimeGetSeconds(duration)
        
        if self.isThumbSeek == false {
            self.seekSlider.value = Float(currentTimeInSecond/durationTimeInSecond)
        }
        
        let value = Float64(self.seekSlider.value) * CMTimeGetSeconds(duration)
        
        var hours = value / 3600
        var mins =  (value / 60).truncatingRemainder(dividingBy: 60)
        var secs = value.truncatingRemainder(dividingBy: 60)
        var timeformatter = NumberFormatter()
        timeformatter.minimumIntegerDigits = 2
        timeformatter.minimumFractionDigits = 0
        timeformatter.roundingMode = .down
        guard let hoursStr = timeformatter.string(from: NSNumber(value: hours)), let minsStr = timeformatter.string(from: NSNumber(value: mins)), let secsStr = timeformatter.string(from: NSNumber(value: secs)) else {
            return
        }
        self.lbCurrentTime.text = "\(hoursStr):\(minsStr):\(secsStr)"
        
        hours = durationTimeInSecond / 3600
        mins = (durationTimeInSecond / 60).truncatingRemainder(dividingBy: 60)
        secs = durationTimeInSecond.truncatingRemainder(dividingBy: 60)
        timeformatter = NumberFormatter()
        timeformatter.minimumIntegerDigits = 2
        timeformatter.minimumFractionDigits = 0
        timeformatter.roundingMode = .down
        guard let hoursStr = timeformatter.string(from: NSNumber(value: hours)), let minsStr = timeformatter.string(from: NSNumber(value: mins)), let secsStr = timeformatter.string(from: NSNumber(value: secs)) else {
            return
        }
        self.lbTotalTime.text = "\(hoursStr):\(minsStr):\(secsStr)"
    }

Conclusion

Congratulations! In conclusion, You have learned how to implement essential control functionalities for AVPlayer in iOS using Swift. Most importantly, With the ability to play, pause, seek, and display time control, you can create a seamless video playback experience for your iOS app. Remember to import the AVFoundation framework, set up AVPlayer, and utilize its methods to achieve the desired functionalities. Above all code will be helpful for underrating more about the code!

Feel free to explore additional features and customization options offered by AVPlayer to enhance your video player further. AVPlayer provides a wide range of capabilities to handle various aspects of video playback, such as volume control, fullscreen mode, and more.

Moreover, Stay tuned for more advanced topics and techniques related to AVPlayer in future blog posts. Happy coding!

Resources

AVPlayer Tutorial

Lastly, Discover more about the AVPlayer and its functionalities by watching my detailed video. In Addition, I highly recommend subscribing to my YouTube channel as it will enable me to create more valuable content for your benefit. Watch the video to gain deeper insights into the AVPlayer.

Furthermore here Learn More Coding

Tags
About The Author
Pushpendra Kumar I am passionate about mobile application development and professional developer at Colour Moon Technologies Pvt Ltd (www.thecolourmoon.com). This website I have made so that I can meet with new challenges and can share here.

Leave a reply

Your email address will not be published. Required fields are marked *