Wenfengcheng / xamarin-notes

xamarin journal
MIT License
3 stars 0 forks source link

AVPlayer add subtitles #11

Open Wenfengcheng opened 5 years ago

Wenfengcheng commented 5 years ago
  1. Get data from subtitle url and parse subtitle string to time-content dictionary by using SubtitlesParser.
NSData data = NSData.FromUrl(url);
var parser = new SubParser();
byte[] bytes = data.ToArray();
using (MemoryStream stream = new MemoryStream(bytes)) {
    foreach ( var item in parser.ParseStream(stream)) {
        var subtitle = new NSMutableDictionary();
    subtitle.Add( 
        new NSString("from"),
        NSNumber.FromFloat(item.StartTime/1000.0f)
    );
    subtitle.Add(
        new NSString("to"),
        NSNumber.FromFloat(item.EndTime/1000.0f)
    );

    string content = string.Empty;
    item.Lines.ForEach(l => content += (l + "\n"));
    content = content.Trim('\n');
    subtitle.Add(
        new NSString("text"),
        new NSString(content)
    );

    subtitles.Add(
        subtitle
    );
}
  1. Then according to start time and end time get current time span content:
    for (nuint i = 0; i < payload.Count; ++i ) {
    NSDictionary item = payload.GetItem<NSDictionary>(i);
    NSNumber from = item.ObjectForKey(new NSString("from")) as NSNumber;
    NSNumber to = item.ObjectForKey(new NSString("to")) as NSNumber;
    if ( time.Seconds >= from.FloatValue &&
        time.Seconds < to.FloatValue) {
            text = item.ObjectForKey(new NSString("text")) as NSString;
            break;
        }
    }
  2. AVPlayer add periodicTimeObserver and update subtitle text every interval

Xamarin.AVPlayerVC.Subs