How to get subtitles' currently displayed text

前端 未结 1 594
甜味超标
甜味超标 2021-01-29 12:00

I would like to extract the subtitle text on a paused video frame of external website (like youtube.com) through console.log.

It is assumed that the external website pr

相关标签:
1条回答
  • 2021-01-29 12:28

    You can access the video's .textTracks, from which you'll be able to access its activeCues from where you can get their text value:

    initTrack();
    video.addEventListener('pause', e => {
     const track = [ ...video.textTracks ]
       .find( track => track.mode === "showing" );
     const texts = [...track.activeCues].map( cue => cue.text );
     console.log( texts.join('\n') );
    });
    
    
    // just to make a VTT accessible in Snippet
    function initTrack() {
      const track = document.querySelector("track");
      let vttText = `WEBVTT`;
      for( let i=0; i<35; i++ ) {
        const t1 = (i + '').padStart(2 , '0');
        const t2 = ((i+1) + '').padStart(2 , '0');
        vttText += `
          00:00:${t1}.000 --> 00:00:${t2}.000
          Test${i}`
      }
      const vttBlob = new Blob([vttText], {
        type: 'text/plain'
      });
      track.src = URL.createObjectURL(vttBlob);
    }
    video { max-height: 150px;  }
    ::cue { font-size: 30px }
    <div>
      <video id="video" controls>
        <source src="https://upload.wikimedia.org/wikipedia/commons/a/a4/BBH_gravitational_lensing_of_gw150914.webm">
        <track default kind="captions" label="English" srclang="en"/>
      </video>
    </div>

    And if you wish to do it while it's playing, then you can listen for the cuechange event:

    initTrack();
    video.addEventListener("loadedmetadata", (evt) => {
      const track = [...video.textTracks]
        .find(track => track.mode === "showing");
      track.oncuechange = (evt) => {
        const texts = [...track.activeCues].map(cue => cue.text);
        console.log(texts.join("\n"));
      };
    });
    
    // just to make a VTT accessible in Snippet
    function initTrack() {
      const track = document.querySelector("track");
      let vttText = `WEBVTT`;
      for (let i = 0; i < 35; i++) {
        const t1 = (i + '').padStart(2, '0');
        const t2 = ((i + 1) + '').padStart(2, '0');
        vttText += `
          00:00:${t1}.000 --> 00:00:${t2}.000
          Test${i}`
      }
      const vttBlob = new Blob([vttText], {
        type: 'text/plain'
      });
      track.src = URL.createObjectURL(vttBlob);
    }
    video {
      max-height: 150px;
    }
    
    ::cue {
      font-size: 30px
    }
    <div>
      <video id="video" controls>
        <source src="https://upload.wikimedia.org/wikipedia/commons/a/a4/BBH_gravitational_lensing_of_gw150914.webm">
        <track default kind="captions" label="English" srclang="en"/>
      </video>
    </div>

    0 讨论(0)
提交回复
热议问题