Search code examples
javascriptvideo.js

How to add an audiotrack in video.js?


in the examples of video.js I've found this:

var track = new videojs.AudioTrack({
  id: 'my-spanish-audio-track',
  kind: 'translation',
  label: 'Spanish',
  language: 'es'
});

my question is how it is added if there are no src attribute, from where does it get the track itself? I mean the source itself like mp3 or wav file

from the docs: http://docs.videojs.com/docs/guides/audio-tracks.html


Solution

  • Audio src under the <audio controls> then <source> tag. You should define here or create dynamically this elements.

    You can download example sounds here.

    var player = videojs('my-player');
    
    // Create a track object.
    var track = new videojs.AudioTrack({
      id: 'my-spanish-audio-track',
      kind: 'translation',
      label: 'Spanish',
      language: 'es'
    });
    
    // Add the track to the player's audio track list.
    player.audioTracks().addTrack(track);
    <script src="https://vjs.zencdn.net/5.15/video.js"></script>
    <link href="https://vjs.zencdn.net/5.15/video-js.css" rel="stylesheet" />
    
    
    <audio id="my-player" class="video-js" controls>
      <source id="my-spanish-audio-track" src="https://www.w3schools.com/html/horse.ogg" type="audio/ogg">
    </audio>

    Dynamically;

    var myAudio=document.createElement("audio");
    myAudio.id="my-player";
    myAudio.className="video-js";
    myAudio.setAttribute("controls",true);
    var mySource1=document.createElement("source");
    mySource1.id="my-spanish-audio-track";
    mySource1.src="https://www.w3schools.com/html/horse.ogg";
    mySource1.type="audio/ogg";
    
    myAudio.appendChild(mySource1);
    document.body.appendChild(myAudio);
    
    var player = videojs('my-player');
    
    // Create a track object.
    var track = new videojs.AudioTrack({
      id: 'my-spanish-audio-track',
      kind: 'translation',
      label: 'Spanish',
      language: 'es'
    });
    
    // Add the track to the player's audio track list.
    player.audioTracks().addTrack(track);
    <script src="https://vjs.zencdn.net/5.15/video.js"></script>
    <link href="https://vjs.zencdn.net/5.15/video-js.css" rel="stylesheet"/>
    
    <body>
    
    </body>