MoMN MoMN - 3 months ago 19
Javascript Question

Change video quality with sources pointing to different quality versions

Goal:

I am trying to implement a control with as little code clutter as possible that will allow the change of quality of a video.

Preferences:

The following is what I am given, and I would rather work around it. I am open to using pre-built plugins or a javascript/jquery hack, but would rather not go for a solution that involves reinventing (me or you) the wheel (require the building of a custom video control scheme), but would take it as a last result.

EDIT:

Sorry. Did not mean to have that correlation, as the urls did not reflect any sort of pattern. I oversimplified it, not assuming people would look at the urls for a pattern. But thank you for that start, as I can probably work with that. Sorry again. I will change the urls to not have any pattern.

<video controls preload>
<source label="fullHD" src="http://v.com/lorem.mp4" type="video/mp4">
<source label="720p" src="http://v.com/ipsum.mp4" type="video/mp4" >
<source label="360p" src="http://v.com/dolor.mp4" type="video/mp4">
</video>


Thank you in advance for anybody who can give some insight.

Answer

Sorry for asking. Turns out I was able to solve it pretty much all by myself. Hate those moments. Here is the solution I came up with, which just involves copying the <source> I need based on the label attribute, deleting it, and prepending it into the <video> element:

HTML

<div class='vidcontainer'>
   <select class='qualitypick' autocomplete='off'>
      <option selected>fullHD</option>
      <option>720p</option>
      <option>360p</option>
   </select>";
   <video controls preload>
      <source label="fullHD" src="http://v.com/lorem.mp4" type="video/mp4">
      <source label="720p"   src="http://v.com/ipsum.mp4" type="video/mp4" >
      <source label="360p"   src="http://v.com/dolor.mp4" type="video/mp4">
   </video>
</div>

JAVASCRIPT

$(document).ready(function(){
   $('.qualitypick').change(function(){ 

      //Have several videos in file, so have to navigate directly
      video = $(this).parent().find("video");

      //Need access to DOM element for some functionality
      videoDOM = video.get(0);

      curtime = videoDOM.currentTime;  //Get Current Time of Video
      source = video.find("source[label=" + $(this).textContent + "]"); //Copy Source

      source.remove();                 //Remove the source from select
      video.prepend(source);           //Prepend source on top of options
      video.load();                    //Reload Video
      videoDOM.currentTime = curtime;  //Continue from video's stop
      videoDOM.play();                 //Resume video
   })
})

Although this was not my intention, I hope my answer is of some use. Sorry again for asking before thinking it through.

Comments