user1960169
user1960169

Reputation: 3653

How to play Audio only in a video file in AVPlayer

Is there any way to play audio only in AVPlayerEven though the url stream has both Audio and video?

Upvotes: 5

Views: 3385

Answers (2)

allenh
allenh

Reputation: 6622

You can. I have verified with a local mp4 video. You have to disable the video tracks after the AVPlayerItem loads them.

The simplest implementation looks like this.

let item = AVPlayerItem(url: url)
var token: NSKeyValueObservation!
token = item.observe(\.tracks) { item, _ in
    item.tracks
        .filter { $0.assetTrack?.mediaType == .video }
        .forEach { $0.isEnabled = false }
    token.invalidate()
}
let player = AVPlayer(playerItem: item)
player.play()

Alternatively, you can add a dummy video output. This still consumes resources, however.

let item = AVPlayerItem(url: url)
item.add(AVPlayerItemVideoOutput())
let player = AVPlayer(url: item)

Upvotes: 2

Max Pevsner
Max Pevsner

Reputation: 4104

Make your video player size 0x0 or place it outside of the screen.

Upvotes: 0

Related Questions