为什么audioContext会静音

Why does audioContext mute the sound

我正在尝试做这样的可视化工具:Visualiser Audio js

但是我电脑上的文件不是客户可以选择的。 像这里一样,文件在我的电脑上。

<audio src="a.mp3" id="audioHTML" controls></audio>

我找到了 this person doing it 但是是客户选择了他们想要的文件,那我该怎么做呢?

我试过了,但声音是静音的,这是我的问题。 (当我删除 'var context = new AudioContext();' 声音又回来了,但显然没有视觉效果)

'use strict'

var audio = document.getElementById("audioHTML");
  

function playAudio() {
    audio.play();

    var context = new AudioContext();
    var src = context.createMediaElementSource(audio);
    var analyser = context.createAnalyser();

    var canvas = document.getElementById("canvas");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    var ctx = canvas.getContext("2d");

    src.connect(analyser);
    analyser.connect(context.destination);

   
    analyser.fftSize = 256;
    
    var bufferLength = analyser.frequencyBinCount;
    console.log(bufferLength);
    
   
    var dataArray = new Uint8Array(bufferLength);

    var WIDTH = canvas.width;
    var HEIGHT = canvas.height;

    var barWidth = (WIDTH / bufferLength) * 2.5;
    var barHeight;
    var x = 0;

    function renderFrame() {
      requestAnimationFrame(renderFrame);

      x = 0;

      analyser.getByteFrequencyData(dataArray);

      ctx.fillStyle = "#000";
      ctx.fillRect(0, 0, WIDTH, HEIGHT);

      for (var i = 0; i < bufferLength; i++) {
        barHeight = dataArray[i];
        
        var r = barHeight + (25 * (i/bufferLength));
        var g = 250 * (i/bufferLength);
        var b = 50;

        ctx.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
        ctx.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);

        x += barWidth + 1;
      }
    }

    audio.play();
    renderFrame();
   }
#thefile {
  position: fixed;
  top: 10px;
  left: 10px;
  z-index: 100;
}

#canvas {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

audio {
  position: fixed;
  left: 10px;
  bottom: 10px;
  width: calc(100% - 20px);
}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <link rel="stylesheet" href="style.css" />
</head>
    <body>

        <div id="content">
            <canvas id="canvas"></canvas>
            <button onclick="playAudio()">click</button>
            <audio src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3" id="audioHTML" controls></audio>
        </div>

        <script src="audioVisualiser.js"></script>
    </body>
</html>

对于您的音频元素,尝试将 crossorigin 属性设置为 use-credentials

<audio src="https://..." crossorigin="use-credentials" id="audioHTML" controls></audio>

没有它,您的 AudioContext 中的 MediaElementSourceNode 可能只会输出无声样本,以防止脚本加载跨域资源。