Sample code to play HLS content

Generated on 8/1/2024

1 search

To play HLS content and enhance ad experiences with HLS interstitials, you can refer to the session Enhance ad experiences with HLS interstitials from WWDC 2024. This session provides a comprehensive overview of how to insert ads or other auxiliary content into your main content using HLS interstitials.

Here's a basic example of how you might set up HLS interstitials in your app:

import AVFoundation
import AVKit

// Create an AVPlayer with your primary content URL
let primaryContentURL = URL(string: "https://example.com/primary.m3u8")!
let player = AVPlayer(url: primaryContentURL)

// Create an AVPlayerViewController and present it
let playerViewController = AVPlayerViewController()
playerViewController.player = player

// Present the player view controller
present(playerViewController, animated: true) {
    player.play()
}

// Schedule an interstitial at 5 seconds into the content
let interstitialURL = URL(string: "https://example.com/interstitial.m3u8")!
let interstitialEvent = AVPlayerInterstitialEvent(primaryItem: player.currentItem!, time: CMTime(seconds: 5, preferredTimescale: 1), templateItems: [AVPlayerItem(url: interstitialURL)])

// Add the interstitial event to the player
player.currentItem?.interstitialEventMonitor.add(interstitialEvent)

This code sets up an AVPlayer to play primary content and schedules an interstitial to play at 5 seconds into the content. The interstitial content will play and then resume the primary content after the interstitial completes.

For more detailed information and advanced usage, you can watch the session Enhance ad experiences with HLS interstitials from WWDC 2024.