视频播放器Dplayer如何监听切换清晰度
视频播放器Dplayer如何监听切换清晰度
// 监听playbackratechange事件
const player = new DPlayer({
container: document.getElementById('dplayer'),
video: {
url: 'https://example.com/path/to/video.mp4',
type: 'auto'
}
});
player.on('playbackratechange', function () {
console.log('Switch to new quality');
});
// 监听video:switchQuality事件
const player = new DPlayer({
container: document.getElementById('dplayer'),
video: {
url: 'https://example.com/path/to/video.mp4',
quality: [
{
name: '1080P',
url: 'https://example.com/path/to/video_1080p.mp4',
type: 'normal'
},
{
name: '720P',
url: 'https://example.com/path/to/video_720p.mp4',
type: 'normal'
},
{
name: '480P',
url: 'https://example.com/path/to/video_480p.mp4',
type: 'normal'
}
]
}
});
player.on('video:switchQuality', function (index) {
console.log('Switch to quality ' + index);
});
npm install dplayer --save
<div class="card">
<div id="dplayer"></div>
</div>
</body>
<script src="/dplayer/dist/DPlayer.min.js"></script>
<script>
const dp = new DPlayer({
container: document.getElementById('dplayer'),
video: {
url: '/dplayer/Cosplay Cinematic.mp4',
},
});
</script>
文档:Dplayer
使用Dplayer实现监听切换清晰度的功能需要进行以下步骤:
在Dplayer的配置中添加video
对象中的defaultQuality
属性,将其设置为视频默认质量的索引值。例如,如果视频有三种质量可选,其中默认为第二种,就可以设置为defaultQuality: 1
。
在Dplayer的配置中添加video
对象中的qualities
属性,将其设置为一个数组,包含每种质量的相关信息,如下所示:
qualities: [
{
name: '标清',
url: 'http://example.com/360p.mp4',
type: 'mp4',
},
{
name: '高清',
url: 'http://example.com/720p.mp4',
type: 'mp4',
},
{
name: '超清',
url: 'http://example.com/1080p.mp4',
type: 'mp4',
},
],
其中,name
属性表示质量名称,url
属性表示质量对应的视频地址,type
属性表示视频类型。
dp.video.switchQuality(index)
方法来监听切换清晰度的事件,其中index
为将要切换的清晰度的索引值。完整代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Dplayer切换清晰度示例</title>
<link rel="stylesheet" href="/dplayer/dist/DPlayer.min.css">
</head>
<body>
<div class="card">
<div id="dplayer"></div>
</div>
<script src="/dplayer/dist/DPlayer.min.js"></script>
<script>
const dp = new DPlayer({
container: document.getElementById('dplayer'),
video: {
url: '/dplayer/Cosplay Cinematic.mp4',
defaultQuality: 1, // 默认为高清
qualities: [
{
name: '标清',
url: 'http://example.com/360p.mp4',
type: 'mp4',
},
{
name: '高清',
url: 'http://example.com/720p.mp4',
type: 'mp4',
},
{
name: '超清',
url: 'http://example.com/1080p.mp4',
type: 'mp4',
},
],
},
});
// 监听切换清晰度事件
dp.on('qualitychange', index => {
console.log(`切换到了第 ${index} 种清晰度`);
});
// 切换到高清
dp.video.switchQuality(1);
</script>
</body>
</html>