C#读srt字幕文件,并用于unity视频的字幕

  1. srt字幕格式
    srt字幕包含多个字幕段,每个字幕段由以下几部分组成:
字幕序号
字幕起止时间
字幕内容(可多行)
空白行

例如:

222
00:09:03,560 --> 00:09:04,940
他怎么会来这里

223
00:09:04,950 --> 00:09:06,300
我捡到了他的狗

2.srt字幕文件解析
此处的解析只保存了字幕里面一行的内容

public class SubtitleBlock
{
    public int Index { get; private set; }
    public double Length { get; private set; }
    public double From { get; private set; }
    public double To { get; private set; }
    public string Text { get; private set; }

    public SubtitleBlock(int index, double from, double to, string text)
    {
        this.Index = index;
        this.From = from;
        this.To = to;
        this.Length = to - from;
        this.Text = text;
    }
    public override string ToString()
    {
        return "Index: " + Index + " From: " + From + " To: " + To + " Text: " + Text;
    }
    static public List<SubtitleBlock> ParseSubtitles(string content)
    {
        var subtitles = new List<SubtitleBlock>();
        var regex = new Regex($@"(?<index>\d*\s*)\n(?<start>\d*:\d*:\d*,\d*)\s*-->\s*(?<end>\d*:\d*:\d*,\d*)\s*\n(?<content>.*)\n(?<content2>.*)\n");
        var matches = regex.Matches(content);
        foreach (Match match in matches)
        {
            var groups = match.Groups;
            int ind = int.Parse(groups["index"].Value);
            TimeSpan fromtime, totime;
            TimeSpan.TryParse(groups["start"].Value.Replace(',', '.'), out fromtime);
            TimeSpan.TryParse(groups["end"].Value.Replace(',', '.'), out totime);
            string contenttext = groups["content"].Value;
            subtitles.Add(new SubtitleBlock(ind, fromtime.TotalSeconds, totime.TotalSeconds, contenttext));
        }
        return subtitles;
    }
}

3.在unity里面配合videoplayer播放,完整的代码如下

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using UnityEngine.Video;

public class SubtitleBlock
{
    public int Index { get; private set; }
    public double Length { get; private set; }
    public double From { get; private set; }
    public double To { get; private set; }
    public string Text { get; private set; }

    public SubtitleBlock(int index, double from, double to, string text)
    {
        this.Index = index;
        this.From = from;
        this.To = to;
        this.Length = to - from;
        this.Text = text;
    }
    public override string ToString()
    {
        return "Index: " + Index + " From: " + From + " To: " + To + " Text: " + Text;
    }
    static public List<SubtitleBlock> ParseSubtitles(string content)
    {
        var subtitles = new List<SubtitleBlock>();
        var regex = new Regex($@"(?<index>\d*\s*)\n(?<start>\d*:\d*:\d*,\d*)\s*-->\s*(?<end>\d*:\d*:\d*,\d*)\s*\n(?<content>.*)\n(?<content2>.*)\n");
        var matches = regex.Matches(content);
        foreach (Match match in matches)
        {
            var groups = match.Groups;
            int ind = int.Parse(groups["index"].Value);
            TimeSpan fromtime, totime;
            TimeSpan.TryParse(groups["start"].Value.Replace(',', '.'), out fromtime);
            TimeSpan.TryParse(groups["end"].Value.Replace(',', '.'), out totime);
            string contenttext = groups["content"].Value;
            subtitles.Add(new SubtitleBlock(ind, fromtime.TotalSeconds, totime.TotalSeconds, contenttext));
        }
        return subtitles;
    }
}

public class subtitle : MonoBehaviour
{
    public float offset;
    List<SubtitleBlock> subt;
    public Text subtitletext;
    public VideoPlayer vp;
    string subcontent;
    public TextAsset subTitleSource;
    //IEnumerator GetRequest(string url)
    //{
    //    using (UnityWebRequest req = UnityWebRequest.Get(url))
    //    {
    //        yield return req.SendWebRequest();
    //        if (req.isNetworkError || req.isHttpError)
    //        {
    //            Debug.Log($"{req.error}: {req.downloadHandler.text}");
    //        }
    //        else
    //        {
    //            subcontent = req.downloadHandler.text;
    //        }
    //    }
    //    subt = SubtitleBlock.ParseSubtitles(subcontent);
    //    StartCoroutine(DisplaySubtitles());
    //}
    void Start()
    {
        if (subTitleSource == null) return;

        subt = SubtitleBlock.ParseSubtitles(subTitleSource.text);
        StartCoroutine(DisplaySubtitles());
        StartCoroutine(playvideo());
    }

    public float localtimer;
    void Update()
    {
        if (vp != null && vp.isPlaying) 
            localtimer = (float)vp.time + offset;
    }
    IEnumerator playvideo()
    {
        if (vp != null)
            vp.Play();
        yield return null;
    }
    public IEnumerator DisplaySubtitles()
    {
        for (int j = 0; j < subt.Count; j++)
        {
            var i = subt[j];
            subtitletext.text = "";
            if (i.From <= localtimer && i.To >= localtimer)
            {
                subtitletext.text = i.Text;
                yield return new WaitForSeconds((float)i.Length);

            }
            else if (i.From > localtimer)
            {
                yield return new WaitForSeconds(Mathf.Min((float)i.From - localtimer, 0.1f));
                j--;
            }
        }
        subtitletext.text = "";
        yield return null;
    }

}

注释的这部分可以用于读取网络链接里面文件并解析字幕。

  • 0
    点赞
  • 6
    收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:1024 设计师:我叫白小胖 返回首页
评论

打赏作者

ys999666

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值