代码之家  ›  专栏  ›  技术社区  ›  aman

vttcue未在javascript中检测到视频字幕“\n”

  •  0
  • aman  · 技术社区  · 6 年前

    我在试着播放带字幕的视频。我正在从 subtitles.txt 文件。字幕被正确地提取和播放,但是 next line = '\n' “代码”未检测到。所以请帮帮我。

    我想要的输出:

    Golden dreams
    and great heartache
    

    我得到的结果是:

    Golden dreams\nand great heartache
    

    我的 字幕.txt 文件:

    211 --> 223
    "Golden dreams\nand great heartache"
    

    我的代码:

    <html>
    <head>
      <meta charset="utf-8"/>
      <title></title>
    </head>
    <body>
      <video video-player src="video.mp4"></video>
      <script>
        var video_player = document.querySelectorAll('[video-player]')[0];
        
        track_english = video_player.addTextTrack("captions", undefined, "en");
        track_english.mode = "showing";
        subtitles_xhr(function(buffer)
        {
          var file = buffer;
          file = file.split('\n');
          for (var x = 0; x < file.length; x+=2)
          {
            track_english.addCue(new VTTCue(file[x].split(" --> ")[0], file[x].split(" --> ")[1], file[x+1]));
          }
        });
        
        function subtitles_xhr (cb)
        {
          var xhr = new XMLHttpRequest;
          xhr.open('GET', "subtitles.txt");
          xhr.onload = function ()
          {
            cb(xhr.response);
          };
          xhr.send();  
        }
      </script>
    </body>
    </html>
    1 回复  |  直到 6 年前
        1
  •  1
  •   Kaiido NickSlash    6 年前

    你的问题是 \n 实际读取文本文件时显示的字符 \\n 字符。

    这些字符不会被VTTCUE分析器识别为新行,因此需要在第三个参数中替换这些字符。 VTTCUE 构造函数到实际新行, \n .

    // make the file available in StackSnippet
    const txt_uri = URL.createObjectURL(new Blob([String.raw`1 --> 13
    "Golden dreams\nand great heartache"`], {type: 'text/plain'}));
    
    var video_player = document.querySelectorAll('[video-player]')[0];
    
    track_english = video_player.addTextTrack("captions", undefined, "en");
    track_english.mode = "showing";
    subtitles_xhr(function(buffer) {
      var file = buffer;
      file = file.split('\n');
      for (var x = 0; x < file.length; x += 2) {
        let startTime = file[x].split(" --> ")[0],
          endTime = file[x].split(" --> ")[1],
          content = file[x + 1]
           .replace(/\\n/g, '\n'); // here replace all occurrences of '\\n' with '\n'
        track_english.addCue(
          new VTTCue(startTime, endTime, content)
        );
      }
    });
    
    function subtitles_xhr(cb) {
      var xhr = new XMLHttpRequest;
      xhr.open('GET', txt_uri);
      xhr.onload = function() {
        cb(xhr.response);
      };
      xhr.send();
    }
    video{max-height:100vh}
    <video video-player src="https://upload.wikimedia.org/wikipedia/commons/transcoded/a/a4/BBH_gravitational_lensing_of_gw150914.webm/BBH_gravitational_lensing_of_gw150914.webm.480p.webm" autoplay controls></video>