记录:播放器<video>音量增益实现方案

412 阅读1分钟

场景:在web端使用<video>标签进行音视频的播放时,<video>标签默认可以设置的音量是有上限的。这个时候如果要对音视频的音量再作放大,可以借助AudioContext进行实现;

备注:部分API理解不是很透彻,在此只作为一个记录,作为一个思考方向,大佬轻喷。

参考链接:mdn.asprain.cn/docs/Web/AP…

实现:

1.方法初始化

this.topGain = 300; //设置音量增益上限
this.per = 10; //每次音量变化的额度
this.player = document.querySelector('video节点标识'); // 获取<video>节点
this.audioCtx = new AudioContext();
this.source = this.audioCtx.createMediaElementSource(this.player);
this.gainNode = this.audioCtx.createGain();
this.gainNode.gain.value = 0.5;
this.currGain = this.gainNode.gain.value;
this.source.connect(this.gainNode);
this.gainNode.connect(this.audioCtx.destination);

2.调用

//音量增加
let _per = this.per / 100;
this.currGain += _per;
this.gainNode.gain.setValueAtTime(this.currGain, this.audioCtx.currentTime);

//音量减小
let _per = this.per / 100;
this.currGain -= _per;
this.gainNode.gain.setValueAtTime(this.currGain, this.audioCtx.currentTime);