HTML5 Video player-videojs+audio tag for video, audio and subtitle sync playback

Source: Internet
Author: User
Tags rewind

One, Videojs introduction

    1. Reference script, Videojs very for your sake, direct CDN, you do not need to download these code into your own website

      <link href=”http://vjs.zencdn.net/c/video-js.css” rel=”stylesheet”><script src=”http://vjs.zencdn.net/c/video.js”></script>
    2. If you need to support IE8, this JS can automatically generate flash

      <!-- If you‘d like to support IE8 --><script src="http://vjs.zencdn.net/ie8/1.1.2/videojs-ie8.min.js"></script>
    3. Add a HTML5 video tag to the page

      <video id="my_video_1" class="video-js vjs-default-skin"     controls preload="auto" width="640" height="264" poster="my_video_poster.png" data-setup="{}">    <source src="my_video.mp4" type="video/mp4">    <source src="my_video.webm" type="video/webm"></video>

Where post is the video thumbnail, the two source a point to the MP4 video, a point to WEBM video, during the page load process, Video.js will determine which format the browser supports video, will automatically load playable video.
It's simple!

Advanced: Using the API

Get object:
The next one is the ID value of the video tag, which is myplayer the player object.

videojs("my-video").ready(function(){    window.myPlayer = this;    // EXAMPLE: Start playing the video.    myPlayer.play();});
Method:

Get Object

var videoobj = Videojs ("VideoID");

Ready

myPlayer.ready(function(){    //在回调函数中,this代表当前播放器,    //可以调用方法,也可以绑定事件。})

Play:

myPlayer.play();

Time out:

myPlayer.pause();

Get Playback progress:

var whereYouAt = myPlayer.currentTime();

To set the playback progress:

myPlayer.currentTime(120);

Video duration, loading the completed video to know the length of the video, and not in the case of Flash

var howLongIsThis = myPlayer.duration();

The buffer is to return the number of downloads

var whatHasBeenBuffered = myPlayer.buffered();

Percentage of buffering

var howMuchIsDownloaded = myPlayer.bufferedPercent();

Sound size (between 0-1)

var howLoudIsIt = myPlayer.volume();

Set the sound size

myPlayer.volume(0.5);

Get the width of the video

var howWideIsIt = myPlayer.width();

Set width:

myPlayer.width(640);

Get height

var howTallIsIt = myPlayer.height();

Set Height:

myPlayer.height(480);

One Step setting Size:

myPlayer.size(640,480);

Fullscreen

myPlayer.enterFullScreen();

Leave full Screen

myPlayer.enterFullScreen();
Add Event
durationchangeended //播放结束firstplayfullscreenchangeloadedalldataloadeddataloadedmetadataloadstartpause //暂停play  //播放progressseekedseekingtimeupdatevolumechangewaitingresize inheritedvar myFunc = function(){// Do something when the event is fired};
Event Bindings
myPlayer.on("ended", function(){    console.log("end", this.currentTime());});myPlayer.on("pause", function(){    console.log("pause")});

Delete Event

Although the article shows that in the case does not support HTML5, will be flash play, but in support of HTML5 Firefox play MP4, but encountered great difficulty, although the call to Flash, but has been unable to play (but I have always suspected that my Firefox flash has a problem , don't know if it's true). But if you follow Videojs's advice and put in two-format videos, you won't have this problem.

In addition to the writing of video also has a special for flash writing, of course, you can also use this plug-in to achieve pure flash playback (just write Flash that part is good, you can guarantee the unified browsing effect, but iOS browser is not compatible with flash, it is necessary for you to judge to deal with

Second, audio label introduction

JavaScript dynamically creates audio tags

There are two main ways to add audio elements to the page, one is to add the audio code to the HTML, to add some attributes (Autoplay,preload), and so on, as mentioned in the previous article. The other is JS dynamic loading in. The code is as follows:

var audio=document.createlement ("audio");
Audio.src= "Audio/source.ogg";//Path
Audio.play ();

or a little simpler.
Audio=new Audio ("Audio/source.ogg");//path
Audio.play ();

In addition to the audio properties, preload has three different loading methods, we can use the preload= "auto" to achieve automatic audio loading, but we do not have an intuitive way to understand the progress of audio loading, and whether ready to play. This provides a "Canplaythrough" event to listen to whether the audio has been loaded. The code examples are as follows:

<! DOCTYPE html >

Run code copy Code save code (hint: can be edited and run)

The first run time will be long, the second run because the file has been cached locally, the prompt box is immediately displayed.

JavaScript controls audio playback, pause, stop

JS How to control the audio label playback is relatively simple, in the above many cases have been mentioned. Mainly Audio.play (), the same pause is relatively simple audio.pause (); it can be easily done, see here you think you want to stop, also will use this semantic function, hehe, actually not such a audio.stop () Does not stop audio playback.

If you need to stop or replay audio, you must set its currenttime and the following statement is visible:

Audio.currenttime = 0;

Below I give a complete example, including start playback, pause playback, stop playback

<! DOCTYPE html >

Run code copy Code save code (hint: can be edited and run)

Note: The stop in the above code adds pause () and jumps to 50 seconds plus play (). The main reason for this is that once the play starts to stop, you need to set CurrentTime to pause the audio. Another jump to 50 seconds, plus play () is the practice if the audio does not play, the audio will not automatically play, and if the audio in the playback, then jump to 50 seconds of playback, the play () here can be ignored. Of course, the specific situation can be defined by itself.

JavaScript controls the sound size of audio:

Control the size of the sound is relatively simple, probably the same as Play,pause, the main is more than one parameter.

Example: Audio.volume = 0;//means mute audio.volume = 1; Indicates the maximum sound, the sound value can be taken between 0-1

The demo does not write, you can modify the above code to run the contents of the box.

JavaScript controls the Fast forward, rewind, and display progress and duration of audio

Control Fast forward, quick-rewind principle is relatively simple, but is set audio currenttime, the case is as follows

For example: Audio.currenttime + = 10;//10 sec Fast Forward

<! DOCTYPE html >

Run code copy Code save code (hint: can be edited and run)

The way to show progress is also not very complicated, but if you want to implement JS with CSS to do a progress bar simulation may be a little more complicated. If you are familiar with JS and CSS, there are a lot of ideas to solve. You can even make a lot of cool effects. I'm just a little bit here. How long the audio file is called and when it is played to progress.

The length of the call to the audio is not difficult to solve "audio.duration;"

The playback progress of the file is called, and a time listener is needed here. CurrentTime represents the current playback time, and the Timeupdate event is triggered when currenttime changes. Therefore, we monitor the timeupdate, and output currenttime can complete the judgment of the progress. Not much to say, look at the sample code:

<! DOCTYPE html >

Run code copy Code save code (hint: can be edited and run)

OK, the basic operation has been finished.

Finally leave a reference to everyone:
http://msdn.microsoft.com/zh-CN/ie/hh377903
Https://wiki.mozilla.org/Audio_Data_API
http://msdn.microsoft.com/en-us/library/gg589489 (v=vs.85). aspx
http://msdn.microsoft.com/en-us/library/gg589528 (v=vs.85). aspx

Third, videojs+audio tag to achieve video and audio synchronization playback

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<title>online player</title>
<%@ include file= "pages/common/include.jsp"%>
<meta name= "viewport" content= "width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1, User-scalable=no "/>
<link rel= "stylesheet" type= "Text/css" href= "${basepath}css/mobile.css"/>
<link rel= "stylesheet" type= "Text/css" href= "${basepath}css/index.css"/>
<link rel= "stylesheet" type= "Text/css" href= "${basepath}images/icons/iconfont.css"/>
<script type= "Text/javascript" src= "${basepath}scripts/rem.js" ></script>
<!--videojs Reference file--
<link href= "${basepath}jslib/videojs/video-js.css" rel= "stylesheet" type= "Text/css"/>
<script type= "Text/javascript" src= "${basepath}jslib/videojs/video.js" ></script>
<script>
videojs.options.flash.swf = "${basepath}jslib/videojs/video-js.swf";
</script>
<script type= "Text/javascript" >
var player;
Load Video
$ (function () {
Player = Videojs (' video ');
var audio=new audio (vt.basepath+ "Videos/${video.videosubtitlepath}");//path

Start or Resume Playback
Player.on (' Play ', function () {
Audio.play ();
Console.log (' Start/resume playback ');
});

Pause Playback
Player.on (' Pause ', function () {
Audio.pause ();
Console.log (' pause play ');
});

Adjust Volume
Player.on (' Volumechange ', function () {
Audio.volume = Player.volume ();
Console.log (' adjust volume ');
});

Video Jump
Player.on (' seeked ', function () {
Audio.currenttime = Player.currenttime ();
Console.log (' change duration ');
});

Detecting playback time
Player.on (' Timeupdate ', function () {
Play End
if (player.duration ()! = 0 && player.currenttime () = = Player.duration ()) {
Audio.currenttime = 0;
Audio.pause ();
Console.log (' End of play ');
}
var beginTime = 0;
var endTime = 0;
var currenttime = player.currenttime () * 1000;
$ ("#playerShow p"). each (function () {
BeginTime = $ (this). attr ("BeginTime");
EndTime = $ (this). attr ("EndTime");
if (currenttime>begintime && currenttime<endtime) {
$ (this). Siblings ("P"). Removeclass ("FontStyle");
$ (this). addclass ("FontStyle");
var oheight = $ (' #myCaptions '). Height ();
var tmp = $ (this). Next (). Offset (). top-$ (This). Parent (). Offset (). top-oheight*0.5;
TMP = TMP > 0? TMP * -1:0;
$ (this). Animate ($ (this). Parent () [0]). Animate ({margintop:tmp + ' px '}, 500);
$ (this). Parent (). Animate ({margintop:tmp + ' px '}, 300);
}
});
});
});

Click Title Edit
function revise (obj) {
Pause Playback
Theplayer.play (FALSE);
Pop-up Click captions and Input boxes
$ ('. Shak '). Slidedown (500);
$ ('. Revise. Revisemain '). addclass ("Animationactive")
The millisecond value to get the start time of each subtitle when you click on a caption
var beginTime = $ (obj). attr ("BeginTime")/1000;
$ ("#beginTimeForSeek"). Val (beginTime);
$ ("#subtitleId"). Val ($ (obj). attr ("id"));
$ ("#oneSrtBody"). HTML ($ (obj). attr ("Onesrtbody"));
var othersrtbody = $ (obj). attr ("Othersrtbody")
if (othersrtbody) {
$ ("#otherSrtBody"). HTML (othersrtbody);
}
}

Click Enter to confirm the send
function Saverevise () {
var revisecontent = $ ("#reviseContent"). Val ();
if ($.string.isnullorempty (revisecontent)) {
Alertwarn ("Please enter the correct content!") ");
Return
}
var data = Getformdata ("Saverevise");
$.ajax ({
Type: "POST",
url:vt.basepath+ "Saverevise",
Data:data,
Success:function (Result) {
if (result = "1") {
Alertinfo ("The revision has been saved successfully! ", hiderevise);
} else {
Alertwarn ("Revision save failed!") ");
}
}
});
}

Hide Input Box
function Hiderevise () {
var beginTime = $ ("#beginTimeForSeek"). Val ();
Theplayer.seek (BeginTime);
$ ('. Shak '). Hide ();
$ ('. Revise. Revisemain '). Removeclass ("animationactive");
$ ("#reviseContent"). Val ("");
Layer.closeall ("dialog");
}

/**
* Show correction record
*/
function Proofrecord (videoid) {
var layerobject = layer.load (' loading in ');
$.ajax ({
Type: "POST",
url:vt.basepath+ "Getrevisedsubtitle",
Data: {"VideoID": VideoID},
Success:function (data) {
FILLFORMBYTPL (data, "Reviserecordtpl", "Reviserecord");
Layer.close (Layerobject);
}
});
}
</script>

<script type= "text/html" id= "REVISERECORDTPL" >
{{#
var len = d.length;
for (var i=0; i<len; i++) {
}}
<li>
<div class= "Thelilfet" >{{d[i].begintimestr.substring (0, 8)}}</div>
<div class= "Theliright" >
<div class= "Translateall" >
<p class= "Translateform" >{{d[i].oneSrtBody}}</p>
{{# if (!$.string.isnullorempty (D[i].othersrtbody)) {}}
<p class= "Translateto" >{{d[i].otherSrtBody}}</p>
{{# } }}
</div>
{{#
var subtitlereviselist = d[i].subtitlereviselist;
var len1 = subtitlereviselist.length;
for (var j=0; j<len1; J + +) {
var srcbody = subtitlereviselist[j].srtbody;
}}
<div class= "Translate" >{{srcBody}}</div>
{{# } }}
</div>
<div style= "Clear:both;" ></div>
</li>
{{# } }}
</script>
<body ondblclick= "return false;" >
<a href= "Javascript:history.go ( -1)" class= "Iconfont Icon-fanhui" ></a>
<span> subtitle Translation of movies is better than </span>
<section>
<div id= "MyElement" >
<video id= "video" class= "Video-js vjs-default-skin vjs-big-play-centered"
Controls preload= "Auto" width= "100%" height= "250px"
Poster= "${basepath}videos/${video.videofirstthumbpath}" data-setup= ' {"Example_option": true} ' >
<source src= "http://7xl9b8.dl1.z0.glb.clouddn.com/b2d53773-614f-4e75-af76-3fd19eb26d10" type= ' Video/mp4 '/>
</div>
<div id= "Mycaptions" >
<div id= "Playershow" class= "SRT" >
<c:foreach items= "${subtitlelist}" var= "subtitle" >
<p class= "P" id= "${subtitle.id}"
onclick = "revise (this);"
Begintime= "${subtitle.begintime}"
Endtime= "${subtitle.endtime}"
Begintimestr= "${subtitle.begintimestr}"
Onesrtbody= "${subtitle.onesrtbody}"
Othersrtbody= "${subtitle.othersrtbody}" >${subtitle.onesrtbody}<br/>${subtitle.othersrtbody}</p>
</c:forEach>
</div>
</div>
</section>
<footer>
<a class= "proofbtn" onclick= "Proofrecord (' ${video.id} ');" > Proofing Records </a>
</footer>

<div class= "Takenotes" >
<div class= "Close Iconfont Icon-shanchu" ></div>
<ul>
<div id= "Reviserecord" ></div>
</ul>
</div>


<div class= "Shak",
<div class= "close1 iconfont icon-shanchu" ></DIV>
<div class= " Revise,
<div class= "Revisetop";
<p id= "Onesrtbody" ></P>
<p id= "Othersrtbody" ></p>
</div>
<div class= "Revisemain";
<div class= "Revisemainleft";
< Form id= "Saverevise";
<input type= "hidden" name= "UserId" value= "${opuser.id}"/>
<input type= " Hidden "name=" Subtitleid "id=" Subtitleid "/>"
<input type= "hidden" name= "VideoID" value= "${video.id}"/>
<input type= "hidden" id= "Begintimeforseek"/>
<textarea name= "Srtbody" id= "Revisecontent" ></ Textarea>
</form>
</div>
<div class= "revisemainright iconfont icon-qiepian13" onclick= " Saverevise () "></DIV>
<div style=" Clear:both; " ></div>
</div>
</div>
</div>

<script>
$ (function () {
Click Proofing Records
$ ('. Proofbtn '). On (' click ', function () {
Theplayer.play (FALSE);
$ ('. Takenotes '). Slidedown (500);
})
Click Close to change the record
$ ('. Takenotes. Close '). On (' click ', function () {
Theplayer.play (TRUE);
$ ('. Takenotes '). Slideup (500);
})

Click Close to change the record 1
$ ('. Shak. Close1 '). On (' click ', function () {
$ ('. Shak '). Slideup (500);
var beginTime = $ ("#beginTimeForSeek"). Val ();
Theplayer.seek (BeginTime);
})
})

Execution in paused state
function stopanything () {
Playback State execution
function biginanything () {
var mymar=setinterval (marquee,speed);
}
}
Execution in paused state
function stopanything () {

}
(function Bottonm () {
if (document). Height () <$ (window). Height ()) {
$ ('. Bottom_fix '). css ({' position ': ' fixed ', ' bottom ': ' 0px '});
$ (document). Height ($ (window). Height () + ' px ');
}
})();
</script>
</body>

HTML5 Video player-videojs+audio tag for video, audio and subtitles sync playback

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.