经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 软件/图像 » unity » 查看文章
Unity实现卡拉OK歌词过渡效果
来源:jb51  时间:2019/6/19 13:12:19  对本文有异议

好长时间之前做过的一个项目 , 其中设计到用Unity模拟卡拉OK歌词过渡的效果 , 如下图所示 ↓ , 这里简单把原理部分分享一下.
文章目录

  • 演示效果 ↓

  • 歌词效果类 ↓

  • 配套资源下载

演示效果 ↓

1.gif

  • 实现歌词动态调整功能

  • 实现动态读取歌词文件功能

  • 实现歌曲快进快退功能

  • 实现歌曲单字时间匹配功能

  • 实现可动态更换歌词前景色背景色功能

注:

这里为实现精准过渡效果使用的是KSC歌词文件, 并不是LRC文件哦 .

这其中我认为就是如何实现歌词部分的前景色向后景色过渡的效果了, 开始的时候我想的也是很复杂 , 使用Shader的形式实现 ,网上找了一些相关代码 , 发现不是特别理想 , 最终还是自己尝试着用Mask来实现的, 发现效果还不错 !
因为今天下班就过年回家啦! 其他细节之后会完善的 , 今天把工程文件先上传了 .

歌词效果类 ↓

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using System;
  6. using DG.Tweening;
  7. using DG.Tweening.Core;
  8.  
  9. /// <summary>
  10. /// 用于显示歌词过渡的效果
  11. /// 1. 获得路径加载并解析歌词文件信息
  12. /// 2. 判断当前歌曲是否播放( 歌曲暂停的时候歌词效果也暂停 , 歌曲停止的时候歌词效果消失 )
  13. /// 3. 判断歌曲快进或快退事件
  14. /// </summary>
  15. public class LayricPanelEffect : MonoSingleton<LayricPanelEffect>
  16. {
  17.  #region *********************************************************************字段
  18.  
  19.  //由外部传入的声音资源
  20.  [HideInInspector,SerializeField]
  21.  public AudioSource audioSource;
  22.  //歌词前景颜色;歌词后景颜色
  23.  [SerializeField]
  24.  public Color32 frontTextColor = Color.white, backTextColor = Color.black, outlineColor = Color.white;
  25.  //歌词面板的前景部分和后景部分
  26.  public RectTransform rectFrontLyricText, rectBackLyricMask;
  27.  public Slider slider;
  28.  //歌词文件路径
  29.  [HideInInspector,SerializeField]
  30.  public string lyricFilePath;
  31.  
  32.  //是否开始播放当前行歌词内容
  33.  public bool isStartLyricEffectTransition = true;
  34.  //歌词调整进度 ( 纠错 )
  35.  // [HideInInspector]
  36.  public float lyricAdjust = -5f;
  37.  
  38.  //歌词文本信息
  39.  // [HideInInspector]
  40.  [SerializeField,HideInInspector]
  41.  public Text _lyricText;
  42.  public Text _textContentLyric, _textLogMessage;
  43.  
  44.  private Vector2 tempFrontSizeDelta, tempBackSizeDelta;
  45.  
  46.  //用于访问歌词正文部分的内容在KscWord类中
  47.  private KSC.KscWord kscword = new KSC.KscWord ();
  48.  private KSC.KscWord curKscword = new KSC.KscWord ();
  49.  
  50.  //内部定时器( 由外部传入参数来控制 , 用来记录歌曲播放的当前时间轴 )
  51.  private float _timer = 0.00f;
  52.  
  53.  #endregion
  54.  
  55.  /// <summary>
  56.  /// 初始化一些变量
  57.  /// </summary>
  58.  void InitSomething ()
  59.  {
  60.  //坚持对歌词文件进行赋值操作
  61.  if (_lyricText == null || rectFrontLyricText.GetComponent <ContentSizeFitter> () == null) {
  62.  if (rectFrontLyricText.GetComponent <Text> () == null) {
  63.  _lyricText = rectFrontLyricText.gameObject.AddComponent <Text> ();
  64.  }
  65.  _lyricText = rectFrontLyricText.GetComponent <Text> ();
  66.  
  67.  //保持歌词实现自适应
  68.  rectFrontLyricText.GetComponent <ContentSizeFitter> ().horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
  69.  rectFrontLyricText.GetComponent <ContentSizeFitter> ().verticalFit = ContentSizeFitter.FitMode.PreferredSize;
  70.  }
  71.  rectBackLyricMask.GetComponentInChildren <Text> ().text = _lyricText.text;
  72.  
  73.  //歌词颜色的更改初始化
  74.  rectBackLyricMask.GetComponentInChildren <Text> ().color = backTextColor;
  75.  rectBackLyricMask.GetComponentInChildren <Outline> ().effectColor = outlineColor;
  76.  rectFrontLyricText.GetComponent <Text> ().color = frontTextColor;
  77.  
  78.  //歌词过渡的前景部分 ( 用于判断过度遮罩的长度范围 )
  79.  tempFrontSizeDelta = rectFrontLyricText.sizeDelta;
  80.  tempBackSizeDelta = rectBackLyricMask.sizeDelta;
  81.  
  82.  //是否开始当前歌词行播放标志位
  83.  isStartLyricEffectTransition = true;
  84.  }
  85.  
  86.  void Awake ()
  87.  { 
  88.  //初始化
  89.  InitSomething ();
  90.  }
  91.  
  92.  /// <summary>
  93.  /// 控制歌词面板的显示
  94.  /// 1. 仅仅显示歌词面板信息 , 没有过渡效果!
  95.  /// </summary>
  96.  /// <param name="row">歌词正文部分行号.</param>
  97.  /// <param name="isPanelView">If set to <c>true</c> 显示面板歌词</param>
  98.  public void LyricPanelControllerView (KSC.KscWord curRowInfo, bool isPanelView)
  99.  {
  100. // Debug.Log ("当前行是否开始=====>" + isPanelView.ToString ());
  101.  _textLogMessage.text = isStartLyricEffectTransition.ToString ();
  102.  
  103.  rectBackLyricMask.sizeDelta = new Vector2 (0f, rectFrontLyricText.sizeDelta.y);
  104.  
  105.  rectBackLyricMask.GetComponentInChildren <Text> ().text = _lyricText.text = "";
  106.  if (isPanelView) {
  107.  //根据时间得到当前播放的是第i行的歌词
  108.  //处理歌词面板信息 , 显示歌词
  109.  foreach (var item in curRowInfo.PerLineLyrics) {
  110.  _lyricText.text += item;
  111.  rectBackLyricMask.GetComponentInChildren<Text> ().text = _lyricText.text;
  112.  }
  113.  StartCoroutine (LyricPanelControllerEffect (curRowInfo, isPanelView));
  114.  } else {
  115.  StopAllCoroutines ();
  116.  rectBackLyricMask.sizeDelta = new Vector2 (0f, rectFrontLyricText.sizeDelta.y);
  117. // StartCoroutine (LyricPanelControllerEffect (curRowInfo, isPanelView));
  118.  //当前歌词结束以后将歌词框初始化成0
  119.  rectBackLyricMask.GetComponentInChildren <Text> ().text = _lyricText.text = string.Empty;
  120.  }
  121.  }
  122.  
  123.  /// <summary>
  124.  /// 开始实现歌此过渡效果, 仅仅效果实现
  125.  /// 1. 使用Dotween的doSizedata实现
  126.  /// 2. 动态调整蒙板的sizedata宽度
  127.  /// 3. 根据歌曲当前播放的时间进度进行调整
  128.  /// </summary>
  129.  /// <returns>The panel controller effect.</returns>
  130.  /// <param name="isPanelEffect">If set to <c>true</c> is panel effect.</param>
  131.  public IEnumerator LyricPanelControllerEffect (KSC.KscWord curRowInfo, bool isPanelEffect)
  132.  {
  133.  //当前时间歌词播放进度的百分比比例
  134.  int curWordIndex = 0;
  135.  if (isPanelEffect) {
  136.  rectBackLyricMask.DORewind ();
  137.  yield return null;
  138.  rectBackLyricMask.sizeDelta = new Vector2 (0f, rectFrontLyricText.sizeDelta.y);
  139.  //开始效果过渡
  140.  if (audioSource.isPlaying) {
  141.  for (int i = 0; i < curKscword.PerLinePerLyricTime.Length; i++) {
  142.  rectBackLyricMask.DOSizeDelta (
  143.  new Vector2 (((float)(+ 1) / curKscword.PerLinePerLyricTime.Length) * rectFrontLyricText.sizeDelta.x, rectFrontLyricText.sizeDelta.y)
  144.  , curKscword.PerLinePerLyricTime [i] / 1000f
  145.  , false).SetEase (Ease.Linear);
  146. // Debug.Log ("第" + i + "个歌词时间");
  147.  yield return new WaitForSeconds (curKscword.PerLinePerLyricTime [i] / 1000f);
  148.  }
  149.  } else {
  150.  Debug.LogError ("歌曲没有播放 !!!!");
  151.  }
  152.  } else {
  153.  yield return null;
  154.  rectBackLyricMask.DOSizeDelta (new Vector2 (0f, rectFrontLyricText.sizeDelta.y), 0f, true);
  155.  }
  156.  }
  157.  
  158.  /// <summary>
  159.  /// 开始播放音乐的时候调用
  160.  /// </summary>
  161.  /// <param name="lyricFilePath">歌词文件路径.</param>
  162.  /// <param name="audioSource">Audiosource用于判断播放状态.</param>
  163.  /// <param name="frontColor">前景色.</param>
  164.  /// <param name="backColor">后景.</param>
  165.  /// <param name="isIgronLyricColor">如果设置为 <c>true</c> 则使用系统配置的默认颜色.</param>
  166.  public void StartPlayMusic (string lyricFilePath, AudioSource audioSource, Color frontColor, Color backColor, Color outlineColor, bool isIgronLyricColor)
  167.  {
  168.  _timer = 0f;
  169.  
  170.  //初始化ksc文件
  171.  KSC.InitKsc (lyricFilePath);
  172.  
  173.  this.lyricFilePath = lyricFilePath;
  174.  this.audioSource = audioSource;
  175.  
  176.  _textContentLyric.text = string.Empty;
  177.  
  178.  if (!isIgronLyricColor) {
  179.  //歌曲颜色信息
  180.  this.frontTextColor = frontColor;
  181.  this.backTextColor = backColor;
  182.  this.outlineColor = outlineColor;
  183.  }
  184.  
  185.  #region ****************************************************输出歌词文件信息
  186.  //对初始化完成后的信息进行输出
  187.  if (KSC.Instance.SongName != null) {
  188.  print ("歌名==========>" + KSC.Instance.SongName);
  189.  }
  190.  if (KSC.Instance.Singer != null) {
  191.  print ("歌手==========>" + KSC.Instance.Singer);
  192.  }
  193.  if (KSC.Instance.Pinyin != null) {
  194.  print ("拼音==========>" + KSC.Instance.Pinyin);
  195.  }
  196.  if (KSC.Instance.SongClass != null) {
  197.  print ("歌类==========>" + KSC.Instance.SongClass);
  198.  }
  199.  if (KSC.Instance.InternalNumber > 0) {
  200.  print ("歌曲编号=======>" + KSC.Instance.InternalNumber);
  201.  }
  202.  if (KSC.Instance.Mcolor != Color.clear) {
  203.  print ("男唱颜色=======>" + KSC.Instance.Mcolor);
  204.  }
  205.  if (KSC.Instance.Mcolor != Color.clear) {
  206.  print ("女唱颜色=======>" + KSC.Instance.Wcolor);
  207.  }
  208.  if (KSC.Instance.SongStyle != null) {
  209.  print ("风格==========>" + KSC.Instance.SongStyle);
  210.  }
  211.  if (KSC.Instance.WordCount > 0) {
  212.  print ("歌名字数=======>" + KSC.Instance.WordCount);
  213.  }
  214.  if (KSC.Instance.LangClass != null) {
  215.  print ("语言种类=======>" + KSC.Instance.LangClass);
  216.  }
  217.  
  218.  //一般是独唱歌曲的时候使用全Tag标签展现参数信息
  219.  foreach (var item in KSC.Instance.listTags) {
  220.  print (item);
  221.  }
  222.  #endregion
  223.  
  224.  //显示整个歌词内容
  225.  for (int i = 0; i < KSC.Instance.Add.Values.Count; i++) {
  226.  KSC.Instance.Add.TryGetValue (i, out kscword);
  227.  for (int j = 0; j < kscword.PerLineLyrics.Length; j++) {
  228.  _textContentLyric.text += kscword.PerLineLyrics [j];
  229.  }
  230.  _textContentLyric.text += "\n";
  231.  }
  232.  }
  233.  
  234.  /// <summary>
  235.  /// 停止播放按钮
  236.  /// </summary>
  237.  public void StopPlayMusic ()
  238.  {
  239.  Debug.Log ("停止播放按钮");
  240.  }
  241.  
  242.  /// <summary>
  243.  /// 主要用于歌词部分的卡拉OK过渡效果
  244.  /// 1. 动态赋值歌词框的长度
  245.  /// 2. 支持快进快退同步显示
  246.  /// </summary>
  247.  int row = 0, tempRow = 0;
  248.  
  249.  void FixedUpdate ()
  250.  {
  251.  #region *********************************************************播放过渡效果核心代码
  252.  //如果是播放状态并且没有快进或快退 , 获得当前播放时间 , 如果都下一句歌词了 , 则切换到下一句歌词进行过渡效果
  253.  //1. 是否是暂停;
  254.  //2. 是否开始播放
  255.  //3. 是否播放停止
  256.  if (audioSource != null && audioSource.isPlaying) {
  257.  //进度条
  258.  slider.value = _timer / audioSource.clip.length;
  259.  //快进快退快捷键
  260.  if (Input.GetKey (KeyCode.RightArrow)) {
  261.  audioSource.time = Mathf.Clamp ((audioSource.time + 1f), 0f, 4.35f * 60f);
  262.  } else if (Input.GetKey (KeyCode.LeftArrow)) {
  263.  audioSource.time = Mathf.Clamp ((audioSource.time - 1f), 0f, 4.35f * 60f);
  264. // } else if (Input.GetKeyUp (KeyCode.LeftArrow)) {
  265.  isStartLyricEffectTransition = true;
  266.  rectBackLyricMask.GetComponentInChildren <Text> ().text = rectFrontLyricText.GetComponent <Text> ().text = string.Empty;
  267.  }
  268.  
  269.  //实时计时
  270.  _timer = audioSource.time;
  271.  
  272.  //歌曲开始播放的时间
  273.  _textLogMessage.text = _timer.ToString ("F2");
  274.  
  275.  for (int i = 0; i < KSC.Instance.Add.Count; i++) {
  276.  
  277.  KSC.Instance.Add.TryGetValue (i, out kscword);
  278.  
  279.  //根据时间判断当前播放的是哪一行的歌词文件 ( 减去0.01可保证两句歌词衔接太快的时候的bug )
  280.  if ((_timer >= (kscword.PerLineLyricStartTimer + lyricAdjust + 0.1f) && _timer <= (kscword.PerLintLyricEndTimer + lyricAdjust - 0.1f)) && isStartLyricEffectTransition) {
  281.  tempRow = i;
  282.  KSC.Instance.Add.TryGetValue (tempRow, out curKscword);
  283.  isStartLyricEffectTransition = false;
  284.  Debug.Log ("当前播放====>" + i + "行");
  285.  //歌词面板显示当前播放内容
  286.  LyricPanelControllerView (curKscword, !isStartLyricEffectTransition);
  287.  } else if ((_timer >= (curKscword.PerLintLyricEndTimer + lyricAdjust)) && !isStartLyricEffectTransition) {
  288.  isStartLyricEffectTransition = true;
  289.  //设置不显示歌词内容
  290.  LyricPanelControllerView (curKscword, !isStartLyricEffectTransition);
  291.  } 
  292.  }
  293.  
  294. // KSC.Instance.Add.TryGetValue (row, out kscword);
  295. //
  296. // //根据时间判断当前播放的是哪一行的歌词文件 ( 减去0.01可保证两句歌词衔接太快的时候的bug )
  297. // if ((_timer >= (kscword.PerLineLyricStartTimer + lyricAdjust + 0.1f) && _timer <= (kscword.PerLintLyricEndTimer + lyricAdjust)) && isStartLyricEffectTransition) {
  298. // tempRow = row;
  299. // KSC.Instance.Add.TryGetValue (tempRow, out curKscword);
  300. // isStartLyricEffectTransition = false;
  301. // Debug.Log ("当前播放====>" + row + "行");
  302. // //歌词面板显示当前播放内容
  303. // LyricPanelControllerView (curKscword, !isStartLyricEffectTransition);
  304. // } else if ((_timer >= (curKscword.PerLintLyricEndTimer + lyricAdjust)) && !isStartLyricEffectTransition) {
  305. // isStartLyricEffectTransition = true;
  306. // //设置不显示歌词内容
  307. // LyricPanelControllerView (curKscword, !isStartLyricEffectTransition);
  308. // row = (row + 1) % KSC.Instance.Add.Count;
  309. // } 
  310.  #endregion
  311.  }
  312.  }
  313. }

###KSC文件解析类 ↓

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System.IO;
  5. using System.Text;
  6. using UnityEngine.UI;
  7. using System;
  8. using System.Text.RegularExpressions;
  9. using System.Runtime.InteropServices;
  10.  
  11. /// <summary>
  12. /// KSC歌词文件解析属性, 单例工具类 ( 解析解析解析解析解析解析解析解析解析!!!!!!重要的事情多说几遍 )
  13. /// 1. 歌词部分标题信息用单例instance访问
  14. /// 2. 正文信息部分使用KSCWord对象访问( 每句开始时间\结束时间\每句歌词文字的数组\每句歌词文件时间的数组 )
  15. /// </summary>
  16. public class KSC : Singleton<KSC>
  17. {
  18.  /// <summary>
  19.  /// 歌曲 歌名
  20.  /// </summary>
  21.  public string SongName { get; set; }
  22.  
  23.  /// <summary>
  24.  /// 歌名字数 歌名字数
  25.  /// </summary>
  26.  public int WordCount{ get; set; }
  27.  
  28.  /// <summary>
  29.  /// 歌名字数 歌名的拼音声母
  30.  /// </summary>
  31.  public string Pinyin{ get; set; }
  32.  
  33.  /// <summary>
  34.  /// 歌名字数 歌曲语言种类
  35.  /// </summary>
  36.  public string LangClass{ get; set; }
  37.  
  38.  /// <summary>
  39.  /// 歌类,如男女乐队等
  40.  /// </summary>
  41.  public string SongClass{ get; set; }
  42.  
  43.  /// <summary>
  44.  /// 艺术家 演唱者,对唱则用斜杠"/"分隔
  45.  /// </summary>
  46.  public string Singer { get; set; }
  47.  
  48.  /// <summary>
  49.  /// 歌曲编号 歌曲编号
  50.  /// </summary>
  51.  public int InternalNumber{ get; set; }
  52.  
  53.  /// <summary>
  54.  /// 歌曲风格
  55.  /// </summary>
  56.  public string SongStyle{ get; set; }
  57.  
  58.  /// <summary>
  59.  /// 视频编号 
  60.  /// </summary>
  61.  public string VideoFileName{ get; set; }
  62.  
  63.  /// <summary>
  64.  /// 前景颜色
  65.  /// </summary>
  66.  public Color Mcolor{ get; set; }
  67.  
  68.  /// <summary>
  69.  /// 后景颜色
  70.  /// </summary>
  71.  public Color Wcolor{ get; set; }
  72.  
  73.  /// <summary>
  74.  /// 偏移量
  75.  /// </summary>
  76.  public string Offset { get; set; }
  77.  
  78.  /// <summary>
  79.  /// 各类标签
  80.  /// </summary>
  81.  public List<string> listTags = new List<string> ();
  82.  
  83.  /// <summary>
  84.  /// 歌词正文部分信息 ( key = 行号 value = 解析出来的歌词正文部分的每句歌词信息 )
  85.  /// </summary>
  86.  public Dictionary<int,KscWord> Add = new Dictionary<int, KscWord> ();
  87.  
  88.  
  89.  /// <summary>
  90.  /// 获得歌词信息
  91.  /// </summary>
  92.  /// <param name="LrcPath">歌词路径</param>
  93.  /// <returns>返回歌词信息(Lrc实例)</returns>
  94.  public static KSC InitKsc (string LrcPath)
  95.  {
  96.  int row = 0;
  97.  //KscWord对象
  98.  //清除之前的歌曲歌词, 保持当前
  99.  KSC.Instance.Add.Clear ();
  100.  using (FileStream fs = new FileStream (LrcPath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
  101.  string line = string.Empty;
  102.  using (StreamReader sr = new StreamReader (fs, Encoding.Default)) {
  103.  
  104.  while ((line = sr.ReadLine ()) != null) {
  105.  //每次循环新建一个对象用于存储不同行数内容
  106.  KSC.KscWord kscWord = new KSC.KscWord ();
  107.  #region ######################################合唱歌曲格式
  108.  if (line.StartsWith ("karaoke.songname := '")) {
  109.  Instance.SongName = SplitStrInfo (line);
  110.  } else if (line.StartsWith ("karaoke.internalnumber := ")) {
  111.  if (SplitIntInfo (line) != 0) {
  112.  Instance.InternalNumber = SplitIntInfo (line);
  113.  }
  114.  } else if (line.StartsWith ("karaoke.singer := '")) {
  115.  Instance.Singer = SplitStrInfo (line);
  116.  } else if (line.StartsWith ("karaoke.wordcount := ")) {
  117.  if (SplitIntInfo (line) != 0) {
  118.  Instance.WordCount = SplitIntInfo (line);
  119.  }
  120.  } else if (line.StartsWith ("karaoke.pinyin := '")) {
  121.  Instance.Pinyin = SplitStrInfo (line);
  122.  } else if (line.StartsWith ("karaoke.langclass := '")) {
  123.  Instance.LangClass = SplitStrInfo (line);
  124.  } else if (line.StartsWith ("karaoke.songclass := '")) {
  125.  Instance.SongClass = SplitStrInfo (line);
  126.  } else if (line.StartsWith ("karaoke.songstyle := '")) {
  127.  Instance.SongStyle = SplitStrInfo (line);
  128.  } else if (line.StartsWith ("karaoke.videofilename :='")) {
  129.  Instance.VideoFileName = SplitStrInfo (line);
  130.  } else if (line.StartsWith ("mcolor :=rgb(")) {
  131.  if (SplitColorInfo (line) != Color.clear) {
  132.  Instance.Mcolor = SplitColorInfo (line);
  133.  }
  134.  } else if (line.StartsWith ("wcolor :=rgb(")) {
  135.  if (SplitColorInfo (line) != Color.clear) {
  136.  Instance.Wcolor = SplitColorInfo (line);
  137.  }
  138.  #endregion
  139.  
  140.  #region ##################################################独唱歌曲风格
  141.  } else if (line.StartsWith ("karaoke.tag('")) {
  142.  //获取tag标签的参数信息
  143.  KSC.Instance.listTags.Add (SplitTagInfo (line));
  144.  #endregion 
  145.  
  146.  #region ################################################歌词正文部分解析
  147.  } else if (line.StartsWith (("karaoke.add"))) {   //表示歌词正文部分
  148.  if (SplitLyricStartTime (line) != null) {
  149.  //行号 ( 从0行开始 )
  150.  
  151.  //获取每句歌词部分的开始时间
  152.  kscWord.PerLineLyricStartTimer = SplitLyricStartTime (line);
  153.  //获取每句歌词部分的结束时间
  154.  kscWord.PerLintLyricEndTimer = SplitLyricEndTime (line);
  155.  //获取每行歌词的内容,并存储到KSCWord中 ( 歌词文字的数组信息 左 → 右 )
  156.  kscWord.PerLineLyrics = SplitPerLineLyrics (line);
  157.  //获取每行中单个文字的过渡时间数组 ( 歌词文字过渡时间数组 左 → 右 )
  158.  kscWord.PerLinePerLyricTime = SplitPerLinePerLyricTime (line);
  159.  KSC.Instance.Add.Add (row, kscWord);
  160.  row++;
  161.  }
  162.  } else {
  163.  //忽略ksc文件中的其他部分
  164.  if (line != "" && !line.Contains ("CreateKaraokeObject") && !line.Contains ("karaoke.rows") && !line.Contains ("karaoke.clear;") && !Regex.IsMatch (line, @"^\//")) {
  165.  Debug.LogWarning ("歌词含有不能解析的部分 ===> " + line);
  166.  }
  167.  }
  168.  #endregion
  169.  }
  170.  }
  171.  } 
  172.  Debug.Log ("LyricFileInitialized" + " Path : \n" + LrcPath);
  173.  return Instance;
  174.  }
  175.  
  176.  #region ****************************************************************解析歌词用的正则表达式部分 需更新
  177.  
  178.  /// <summary>
  179.  /// 处理信息(私有方法)
  180.  /// </summary>
  181.  /// <param name="line"></param>
  182.  /// <returns>返回基础信息</returns>
  183.  public static string SplitStrInfo (string line)
  184.  {
  185. // char[] ch = new char[]{ '\0', '\0' };
  186. // return line.Substring (line.IndexOf ("'") + 1).TrimEnd (ch);
  187.  string pattern = @"'\S{1,20}'"; //获取歌曲标签信息
  188.  Match match = Regex.Match (line, pattern);
  189.  
  190.  //去除两端的小分号
  191.  string resout = string.Empty;
  192.  resout = match.Value.Replace ("\'", string.Empty);
  193.  return resout;
  194.  }
  195.  
  196.  /// <summary>
  197.  /// 处理参数是数字的情况
  198.  /// </summary>
  199.  /// <returns>The int info.</returns>
  200.  /// <param name="line">Line.</param>
  201.  public static int SplitIntInfo (string line)
  202.  {
  203.  string pattern = @"\d+"; //获取歌曲标签参数为数字的信息
  204.  Match match = Regex.Match (line, pattern);
  205.  
  206.  //去除两端的小分号
  207.  int result = 0;
  208.  result = Int32.Parse (match.Value);
  209.  return result;
  210.  }
  211.  
  212.  /// <summary>
  213.  /// 处理参数颜色色值的情况 如: mcolor :=rgb(0, 0, 255);
  214.  /// </summary>
  215.  /// <returns>The color info.</returns>
  216.  /// <param name="line">Line.</param>
  217.  public static Color32 SplitColorInfo (string line)
  218.  {
  219.  string pattern = @"[r,R][g,G][b,G]?[\(](2[0-4][0-9])|25[0-5]|[01]?[0-9][0-9]?"; //获取歌曲标签参数为颜色值的信息
  220.  MatchCollection matches = Regex.Matches (line, pattern);
  221.  
  222.  return new Color (float.Parse (matches [0].ToString ()), float.Parse (matches [1].ToString ()), float.Parse (matches [2].ToString ()));
  223.  }
  224.  
  225.  /// <summary>
  226.  /// 获取歌曲的标签部分信息 如 : karaoke.tag('语种', '国语'); // 国语/粤语/台语/外语
  227.  /// </summary>
  228.  /// <returns>The tag info.</returns>
  229.  public static string SplitTagInfo (string line)
  230.  {
  231.  string temp;
  232.  string pattern = @"\([\W|\w]+\)"; //获取歌曲标签参数为颜色值的信息
  233.  Match match = Regex.Match (line, pattern);
  234.  temp = match.Value.Replace ("(", string.Empty).Replace (")", string.Empty).Replace ("'", string.Empty).Replace (",", ":");
  235.  return temp;
  236.  }
  237.  
  238.  /// <summary>
  239.  /// 获取每句歌词正文部分的开始时间 (单位 : 秒)
  240.  /// </summary>
  241.  /// <returns>The lyric start time.</returns>
  242.  /// <param name="line">Line.</param>
  243.  public static float SplitLyricStartTime (string line)
  244.  {
  245.  float time = 0f;
  246.  Regex regex = new Regex (@"\d{2}:\d{2}\.\d{2,3}", RegexOptions.IgnoreCase); //匹配单句歌词时间 如: karaoke.add('00:29.412', '00:32.655'
  247.  MatchCollection mc = regex.Matches (line);
  248.  time = (float)TimeSpan.Parse ("00:" + mc [0].Value).TotalSeconds;
  249.  return time;
  250.  }
  251.  
  252.  /// <summary>
  253.  /// 获取每句歌词正文部分的结束时间 (单位 : 秒)
  254.  /// </summary>
  255.  /// <returns>The lyric start time.</returns>
  256.  /// <param name="line">Line.</param>
  257.  public static float SplitLyricEndTime (string line)
  258.  {
  259.  Regex regex = new Regex (@"\d{2}:\d{2}\.\d{2,3}", RegexOptions.IgnoreCase); //匹配单句歌词时间 如: karaoke.add('00:29.412', '00:32.655'
  260.  MatchCollection mc = regex.Matches (line);
  261.  float time = (float)TimeSpan.Parse ("00:" + mc [1].Value).TotalSeconds;
  262.  return time;
  263.  }
  264.  
  265.  /// <summary>
  266.  /// 获取每句歌词部分的每个文字 和 PerLinePerLyricTime相匹配 (单位 : 秒)
  267.  /// </summary>
  268.  /// <returns>The line lyrics.</returns>
  269.  /// <param name="line">Line.</param>
  270.  public static string[] SplitPerLineLyrics (string line)
  271.  {
  272.  List<string> listStrResults = new List<string> ();
  273.  string pattern1 = @"\[[\w|\W]{1,}]{1,}"; //获取歌曲正文每个单词 如 : karaoke.add('00:25.183', '00:26.730', '[五][十][六][个][星][座]', '312,198,235,262,249,286');
  274.  string pattern2 = @"\'(\w){1,}\'"; //获取歌曲正文每个单词 如 : karaoke.add('00:28.420', '00:35.431', '夕阳底晚风里', '322,1256,2820,217,1313,1083');
  275.  Match match = (line.Contains ("[") && line.Contains ("]")) ? Regex.Match (line, pattern1) : Regex.Match (line, pattern2);
  276.  //删除掉 [ ] '
  277.  if (match.Value.Contains ("[") && match.Value.Contains ("]")) { //用于合唱类型的歌词文件
  278.  string[] resultStr = match.Value.Replace ("][", "/").Replace ("[", string.Empty).Replace ("]", string.Empty).Split ('/');
  279.  foreach (var item in resultStr) {
  280.  listStrResults.Add (item);
  281.  }
  282.  } else if (match.Value.Contains ("'")) {  //用于独唱类型的歌词文件 ( 尚未测试英文歌词文件!!!!!!!!!!!!!!!!!!!!!!! )
  283.  char[] tempChar = match.Value.Replace ("'", string.Empty).ToCharArray ();
  284.  foreach (var item in tempChar) {
  285.  listStrResults.Add (item.ToString ());
  286.  }
  287.  }
  288.  return listStrResults.ToArray ();
  289.  }
  290.  
  291.  /// <summary>
  292.  /// 获取每句歌词部分的每个文字需要的过渡时间 和 PerLineLyrics相匹配 (单位 : 秒)
  293.  /// </summary>
  294.  /// <returns>The line per lyric time.</returns>
  295.  /// <param name="line">Line.</param>
  296.  public static float[] SplitPerLinePerLyricTime (string line)
  297.  {
  298.  string pattern = @"\'((\d){0,}\,{0,1}){0,}\'"; //获取歌曲正文每个单词过渡时间 如 : karaoke.add('00:25.183', '00:26.730', '[五][十][六][个][星][座]', '312,198,235,262,249,286');
  299.  
  300.  string str = null;
  301.  List<float> listfloat = new List<float> ();
  302.  //删除掉 多余项
  303.  str = Regex.Match (line, pattern).Value.Replace ("'", string.Empty);
  304. // Debug.Log (str);
  305.  foreach (var item in str.Split (',')) {
  306.  listfloat.Add (float.Parse (item));
  307.  }
  308.  return listfloat.ToArray ();
  309.  }
  310.  
  311.  #endregion
  312.  
  313.  #region ********************************************************************歌词正文部分的时间与文字信息
  314.  
  315.  /// <summary>
  316.  /// 用单独的类来管理歌词的正文部分 ( 在KSC类下 )主要用来存储每句歌词和每个歌词的时间信息
  317.  /// 1. 每句歌词的时间的 ( 开始 - 结束 )
  318.  /// 2. 每句歌词中单个文字的时间信息 (集合的形式实现)
  319.  /// </summary>
  320.  public class KscWord
  321.  {
  322.  /// <summary>
  323.  /// 每行歌词部分开始的时间 (单位 : 秒) (key=行号,value=时间)
  324.  /// </summary>
  325.  public float PerLineLyricStartTimer { get; set; }
  326.  
  327.  /// <summary>
  328.  /// 每行歌词部分结束时间 (单位 : 秒) (key=行号,value=时间)
  329.  /// </summary>
  330.  public float PerLintLyricEndTimer { get; set; }
  331.  
  332.  /// <summary>
  333.  /// 每行歌词的单个文字集合
  334.  /// </summary>
  335.  public string[] PerLineLyrics{ get; set; }
  336.  
  337.  /// <summary>
  338.  /// 每行歌词中单个文字的速度过渡信息 (单位 : 毫秒)
  339.  /// </summary>
  340.  public float[] PerLinePerLyricTime{ get; set; }
  341.  }
  342.  
  343.  #endregion
  344. }

不敢说代码如何清新脱俗 , 自己也在学习的路上 , 有程序爱好者想要交流的话欢迎交流啊 . 有心的朋友可以看看 , 年后看时间再完善啦

配套资源下载

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号