Controlling Video Playback with AVPlayer in SwiftUI

AVPlayer comes with multiple built-in controls so you can control how your video is shown to the user. Learn how to set up an AVPlayer in your SwiftUI application by reading the Videos with AVPlayer section.

Play, pause, change the video speed, get the current time or the duration, and add subtitles to a video, all using AVPlayer

Automatically play the video 

To automatically play the video, add player.play() in the .onAppear modifier:

.onAppear() {
	player.play()
}

..

Pause the video 

To pause the video, simply call the .pause() method on your player:

player.pause()

..

Set a start time

By default, the start time is at 0 seconds. However, if you want to set another start time, it's easy to do so with the .seek method that comes with AVPlayer.

Add a videoStartTime variable at the top of your file. Remember that this variable is of CMTime type, which is a time value. To create a CMTime variable from an Integer, you'll need CMTimeMake, which takes two values in the parenthesis. These two values are a fraction. The value is the numerator, and timescale is the denominator.

@State var videoStartTime: CMTime = CMTimeMake(value: 10, timescale: 1)

..

In the code above, we are setting the videoStartTime at 10/1 seconds, so at 10 seconds (remember that CMTimeMake creates a fraction). 

Then, in the .onAppear modifier, simply add a .seek method to the player, and set it to videoStartTime:

.onAppear {
		player.seek(to: videoStartTime)
}

..

Your video will now automatically play and start at 10 seconds.

Set a play rate

To set a default play rate to your video player, call .rate and set it to the the video speed you desire.

player.rate = 1.5

..

It's important to set the rate after calling player.play() so that it works.

Get current video time 

To get the current time of the video, call the .currentTime() method on the player:

player.currentTime()

This will return a CMTime value. To only extract the seconds, see Convert CMTime to seconds below.

..

Get video duration 

To get the duration of the video, call .currentItem!.asset.duration on the player:

player.currentItem!.asset.duration

This will return a CMTime value. To only extract the seconds, see Convert CMTime to seconds below.

..

Convert CMTime to seconds 

To convert a CMTime value into seconds (or simply to only get the seconds out of CMTime), you just need to wrap it in CMTimeGetSeconds:

CMTimeGetSeconds(player.currentTime())

..

Show subtitles

Make sure your video link is of HLS format (with the .m3u8 filename extension), which includes the subtitle tracks inside of the mp4 video file. 

Then, automatically, when playing the video, AVPlayer will give the option to the user to enable the subtitles.

More player controls

To read all the methods available with the AVPlayer class, read the Apple Developer's documentation on AVPlayer.

..


Comments