我正在使用 m3u8 视频格式来流式传输视频,现在我需要显示相同的字幕。
我在 Apple 文档中搜索,发现我可以通过使用 closedCaptionDisplayEnabled
来实现这一点。 AVPlayer
的属性(property).
我很想知道字幕的格式应该是什么? .srt 格式可以吗?
我也可以使用 MPMoviePlayerController
达到同样的效果吗? ?
任何帮助表示赞赏。
最佳答案
2020 年 3 月 6 日更新:在 GitHub 上,jbweimar 创建了一个使用 AVAssetResourceLoaderDelegate
的示例项目。看起来很有前途的方法:https://github.com/jbweimar/external-webvtt-example
2018 年 10 月 30 日更新:值得一看this answer by an Apple engineer (感谢 @allenlini 用于 pointing it out )。他提出了一个涉及 AVAssetResourceLoaderDelegate
的解决方案。 .我自己没有尝试过,但它可能是比我下面更好的解决方案。
原答案:
似乎在您的 m3u8 流媒体描述中引用您的 WebVTT 文件是官方支持的方式。 “事后”添加它们似乎不受官方支持(参见 this statement by an Apple engineer (bottom of the page) )。
那 - 但是 - 并不意味着你不能让它工作;-)。
在 this great presentation 的帮助下和 sample project (ZIP)作者:克里斯·亚当森,this post on the Apple Developer Forums和 this Ray Wenderlich tutorial by Abdul Azeem ,我能够让它工作。这是 Abdul Azeem 示例代码和 Chris 示例项目的修改版本。
请注意您需要如何使用 AVMediaTypeText
而不是 AVMediaTypeSubtitle
.这似乎是iOS中的一个错误。
// 1 - Load video asset
AVAsset *videoAsset = [AVURLAsset assetWithURL:[[NSBundle mainBundle] URLForResource:@"video" withExtension:@"mp4"]];
// 2 - Create AVMutableComposition object. This object will hold your AVMutableCompositionTrack instances.
AVMutableComposition *mixComposition = [[AVMutableComposition alloc] init];
// 3 - Video track
AVMutableCompositionTrack *videoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo
preferredTrackID:kCMPersistentTrackID_Invalid];
[videoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration)
ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0]
atTime:kCMTimeZero error:nil];
// 4 - Subtitle track
AVURLAsset *subtitleAsset = [AVURLAsset assetWithURL:[[NSBundle mainBundle] URLForResource:@"subtitles" withExtension:@"vtt"]];
AVMutableCompositionTrack *subtitleTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeText
preferredTrackID:kCMPersistentTrackID_Invalid];
[subtitleTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration)
ofTrack:[[subtitleAsset tracksWithMediaType:AVMediaTypeText] objectAtIndex:0]
atTime:kCMTimeZero error:nil];
// 5 - Set up player
AVPlayer *player = [AVPlayer playerWithPlayerItem: [AVPlayerItem playerItemWithAsset:mixComposition]];
关于mpmovieplayercontroller - AVPlayer/MPMoviePlayerController 的字幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11525342/