[javascript] JS增強HTML媒體資源的音量

NoNoe發表於2024-06-18

pre

有些頁面聲音總是太小,又不想調整系統音量,而video標籤的volume屬性最高只能調到1。於是在網上找到了一個方案:

ref: https://atjiu.github.io/2021/05/10/video-above-1.0/
ref: https://cwestblog.com/2017/08/17/html5-getting-more-volume-from-the-web-audio-api/

code

function amplifyMedia(mediaElem, multiplier) {
  const context = new (window.AudioContext || window.webkitAudioContext)
  const result = {
    context: context,
    source: context.createMediaElementSource(mediaElem),
    gain: context.createGain(),
    media: mediaElem,
    amplify: function (multiplier) { this.gain.gain.value = multiplier },
    getAmpLevel: function () { return this.gain.gain.value }
  }
  result.source.connect(result.gain)
  result.gain.connect(context.destination)
  result.amplify(multiplier)
  return result
}

usage

上面程式碼經過略微修改。實踐中先找到目標<audio> / <video>標籤,然後將其作為amplifyMedia的第一個引數,而音量放大倍數作為其第二個引數傳入,在控制檯執行即可,例如:amplifyMedia(elem, 6)

相關文章