点击下载教程相关资源
播放器的音量可通过播放器上的音量(volume)功能进行更改。volume() 函数接受 0-1 之间的数字。不带参数调用该函数将返回当前音量。例如:
var myPlayer = videojs('some-player-id'); myPlayer.src({type: 'video/mp4', src: 'http://www.example.com/path/to/video.mp4'}); myPlayer.ready(function() { // get var howLoudIsIt = myPlayer.volume(); // set myPlayer.volume(0.5); // Set volume to half });
完整示例:
<html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Video.js</title> <!-- 引入 Video.js 样式 --> <link href="https://vjs.zencdn.net/8.10.0/video-js.css" rel="stylesheet" /> <!-- 如果您想支持 IE8(适用于 v7 之前的 Video.js 版本) --> <!-- <script src="https://vjs.zencdn.net/ie8/1.1.2/videojs-ie8.min.js"></script> --> </head> <body> <div id="container"> <video id="vid1" data-setup='{"preload":"auto","controls":true,"width":"640","height":"264px", "poster":"../resources/oceans.jpg"}'> <source src="../resources/oceans.mp4" type="video/mp4" /> <source src="../resources/oceans.webm" type="video/webm" /> </video> </div> <p>当前音量:<label id="volume"></label></p> <p> <button onclick="add()">增加音量</button> <button onclick="reduce()">减低音量</button> </p> <!-- 引入 Video.js 库 --> <script src="https://vjs.zencdn.net/8.10.0/video.min.js"></script> <script> let player = videojs('vid1'); // 获取当前音量 let howLoudIsIt = player.volume(); function showVolume() { document.getElementById("volume").innerHTML = (howLoudIsIt.toFixed(2) * 100) + "%"; } showVolume(); // 增加音量 function add() { howLoudIsIt += 0.1; howLoudIsIt = Math.min(howLoudIsIt, 1); player.volume(howLoudIsIt); showVolume(); } // 减低音量 function reduce() { howLoudIsIt -= 0.1; howLoudIsIt = Math.max(howLoudIsIt, 0); player.volume(howLoudIsIt); showVolume(); } </script> </body> </html>
运行效果图:
注意:我们还可以使用 muted() 函数对音量进行静音(而不实际改变音量值)。不带参数调用 muted() 函数将返回播放器当前的静音状态。例如:
<html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Video.js</title> <!-- 引入 Video.js 样式 --> <link href="https://vjs.zencdn.net/8.10.0/video-js.css" rel="stylesheet" /> <!-- 如果您想支持 IE8(适用于 v7 之前的 Video.js 版本) --> <!-- <script src="https://vjs.zencdn.net/ie8/1.1.2/videojs-ie8.min.js"></script> --> </head> <body> <div id="container"> <video id="vid1" data-setup='{"preload":"auto","controls":true,"width":"640","height":"264px", "poster":"../resources/oceans.jpg"}'> <source src="../resources/oceans.mp4" type="video/mp4" /> <source src="../resources/oceans.webm" type="video/webm" /> </video> </div> <p>当前静音状态:<label id="status"></label></p> <p> <button onclick="setMuted()">修改静音状态</button> </p> <!-- 引入 Video.js 库 --> <script src="https://vjs.zencdn.net/8.10.0/video.min.js"></script> <script> let player = videojs('vid1'); player.ready(function() { // 获取当前静音状态 show(player.muted()); }); function setMuted() { // 设置静音状态 player.muted(!player.muted()); // 获取当前静音状态 show(player.muted()); } function show(status) { document.getElementById("status").innerHTML = status ? "启用" : "关闭"; } </script> </body> </html>
运行示例,效果图: