Skip to content

Instantly share code, notes, and snippets.

@peatiscoding
Created January 17, 2017 14:53
Show Gist options
  • Save peatiscoding/4f01a64797289fd40793837fb727c9c6 to your computer and use it in GitHub Desktop.
Save peatiscoding/4f01a64797289fd40793837fb727c9c6 to your computer and use it in GitHub Desktop.
import AVFoundation
extension AVPlayerItem {
enum TrackType {
case subtitle
case audio
/**
Return valid AVMediaSelectionGroup is item is available.
*/
fileprivate func characteristic(item:AVPlayerItem) -> AVMediaSelectionGroup? {
let str = self == .subtitle ? AVMediaCharacteristicLegible : AVMediaCharacteristicAudible
if item.asset.availableMediaCharacteristicsWithMediaSelectionOptions.contains(str) {
return item.asset.mediaSelectionGroup(forMediaCharacteristic: str)
}
return nil
}
}
func tracks(type:TrackType) -> [String] {
if let characteristic = type.characteristic(item: self) {
return characteristic.options.map { $0.displayName }
}
return [String]()
}
func selected(type:TrackType) -> String? {
guard let group = type.characteristic(item: self) else {
return nil
}
let selected = self.selectedMediaOption(in: group)
return selected?.displayName
}
func select(type:TrackType, name:String) -> Bool {
guard let group = type.characteristic(item: self) else {
return false
}
guard let matched = group.options.filter({ $0.displayName == name }).first else {
return false
}
self.select(matched, in: group)
return true
}
}
@peatiscoding
Copy link
Author

peatiscoding commented Jan 17, 2017

An easy way to manage AVPlayerItem's track.

Here are some example:

// Simple usage
let player = AVPlayer()
// Get options
let subtitles = player.currentItem?.tracks(.subtitle)
// Get selected track displayName
let selectedSubtitle = player.currentItem?.selected(.subtitle)
// Select track with displayName
var success = player.currentItem?.select(.subtitle, subtitles.first!)

For more info see: http://wp.me/p6YVsq-bO

@SyedGhaus
Copy link

Hi , Just need one help.I am using this class very helpful.But if i am changing the Subtitle and after that audio same time one thing works other dont.Cannot understand why

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment