Search code examples
javascripthtmlvideo.jssubtitle

How can you add a subtitle track dynamically to a video.js video player


That's pretty much it; I need to change the subtitles to the theater of a webpage and if possible, even not have them at all, but mostly I wanna change the subtitles of a videojs player. I could show you the website but don't think it's necessary. I've tried:

videojs(theater_video, {tracks: `<track kind='subtitles' src='/resources/videos/whale_Shailene/Spanish.vtt' srclang='es' label='Español' ></track>
                                 <track kind='subtitles' src='/resources/videos/whale_Shailene/Arabic.vtt' srclang='ar' label='عرب.' ></track>`})

, and:

videojs(theater_video, {tracks: [{
         src: '/resources/videos/whale_Shailene/Spanish.vtt',
         kind:'subtitles',
         srclang: 'es',
         label: 'Español'
      },{
         src: '/resources/videos/whale_Shailene/Arabic.vtt',
         kind:'subtitles',
         srclang: 'ar',
         label: 'عرب.'
      }]})

But neither seem to appear nor even change the subtitles of the player

Neither a combination of either of those with:

$("#theater video").find("source").after(`<track kind='subtitles' src='/resources/videos/whale_Shailene/Spanish.vtt' srclang='es' label='Español' ></track>
                                          <track kind='subtitles' src='/resources/videos/whale_Shailene/Arabic.vtt' srclang='ar' label='عرب.' ></track>`)

I'm using Video.js v4.9.1 :/ And it seems like a tough update because I edited a lot the Video.js css and js files directly

Thanks beforehand


Solution

  • The second option works, as a setup option. If you use that on a player that has already initialised, it does nothing. You can use addRemoteTextTrack() to add a track to a player. See https://videojs.com/guides/text-tracks

    videojs.getPlayer('theater_video').addRemotetextTrack({
      src: '/resources/videos/whale_Shailene/Spanish.vtt',
      kind:'subtitles',
      srclang: 'es',
      label: 'Español'
    });