1、效果图:
2、代码:
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Text.RegularExpressions;
public class CaptionManager : MonoBehaviour
{
//用来显示字幕的TextUi
public Text Titles;
//文件流,用于读取文本
StreamReader sr;
//文本中的字幕的行数
int lineCount = 0;
bool ison;
int videotime;
int listcount;
//先读取到unity里面在进行后面的操作
public List<string> video0 = new List<string>();
public List<int> video0starttime = new List<int>();
public List<int> video0endtime = new List<int>();
public List<string> video1 = new List<string>();
public List<string> video2 = new List<string>();
public List<string> video3= new List<string>();
//地址
string path = "/VideoAndAudio/taici/panduan0.txt";
string path1 = "/VideoAndAudio/taici/panduan1.txt";
string path2 = "/VideoAndAudio/taici/panduan2.txt";
string path3 = "/VideoAndAudio/taici/panduan3.txt";
void Start()
{
LoadText(path, video0);
LoadText(path1, video1);
LoadText(path2, video2);
LoadText(path3, video3);
}
private void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
StartCoroutine(ShowText(video0));
}
}
public void Show(List<string> vide)
{
for (int i = 0; i < vide.Count; i++)
{
string tempText = vide[i];
//没有用null,是因为用null老是隔行读取,读取不完整,发现用("")就可以
if (tempText != "")
{
//检查tempText 是否包含‘|’
string SS = "|";
bool II = tempText.Contains(SS);
if (II)
{
//分割开
string str = tempText.Split('|')[0];
int start = int.Parse((tempText.Split('|')[1]));
int end = int.Parse((tempText.Split('|')[2]));
video0starttime.Add(start);
video0endtime.Add(end);
}
else
{
Debug.Log("文本格式不对");
}
}
}
}
IEnumerator ShowText(List<string> vide0)
{
for (int i = 0; i < vide0.Count; i++)
{
string tempText = vide0[i];
if (tempText != "")
{
string SS = "$";
bool II = tempText.Contains(SS);
if(II)
{
string str = tempText.Split('$')[0];
float time;
Titles.text = str;
if (float.TryParse(tempText.Split('$')[1], out time))
{
yield return new WaitForSeconds(time);
}
}
else
{
Debug.Log("文本格式不对");
break;
}
}
}
}
public void LoadText(string paths,List<string> videotici)
{
string path = Application.dataPath + paths;
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
//TXT保存的也要选择UTF8格式
StreamReader srLine = new StreamReader(fs,System.Text.Encoding.UTF8);
while(srLine.Peek()!=-1)
{
string strs = srLine.ReadLine().Trim();
if (strs != "")
{
videotici.Add(strs);
lineCount++;
}
}
srLine.Close();
srLine.Dispose();
}
}
3、TXT保存格式: