【问题标题】:HTML and JS Based Audio Waveform基于 HTML 和 JS 的音频波形
【发布时间】:2020-01-13 11:03:44
【问题描述】:

我试图通过这篇文章制作音频波可视化

Play a moving waveform for wav audio file in html

这里是代码

<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Audio Visualizer</title>
        <script type="text/javascript" src="visualization.js"></script>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <audio id="audioElement" src="bensound-perception.mp3"></audio>
        <canvas id="wave"></canvas>
        <div>
          <button onclick="audioElement.play()">Play the Audio</button>
          <button onclick="audioElement.pause()">Pause the Audio</button>
          <button onclick="audioElement.volume+=0.1">Increase Volume</button>
          <button onclick="audioElement.volume-=0.1">Decrease Volume</button>
        </div>

        <figure>
            <figcaption>Listen to the Track:</figcaption>
            <audio
                controls
                src="bensound-perception.mp3">
                    Your browser does not support the
                    <code>audio</code> element.
            </audio>
        </figure>
    </body>
</html>

这是 JS 代码

audioElement = document.getElementById('audioElement');
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var audioSrc = audioCtx.createMediaElementSource(audioElement);
var analyser = audioCtx.createAnalyser();

// Bind our analyser to the media element source.
audioSrc.connect(analyser);
audioSrc.connect(audioCtx.destination);

//Get frequency data (800 = max frequency)
var frequencyData = new Uint8Array(400);
//Use below to show all frequencies
//var frequencyData = new Uint8Array(analyser.frequencyBinCount);

//Create canvas
var canvas = document.getElementById("wave");
canvas.style.width = "1000px";
canvas.style.height = "100px";

//High dpi stuff
canvas.width = parseInt(canvas.style.width) * 2;
canvas.height = parseInt(canvas.style.height) * 2;

//Get canvas context
var ctx = canvas.getContext("2d");

//Set stroke color to yellow
ctx.strokeStyle = "#ffff00";

//Draw twice as thick lines due to high dpi scaling
ctx.lineWidth = 2;

//Save x and y from the previous drawing
var drawX = 0;
var drawY = 0;

//Total duration (Seconds)
var duration;

//The animation reference
var animation;

//Audio is loaded
audioElement.oncanplaythrough = function() {

    //Get duration
    duration = audioElement.duration;

    //On play
    audioElement.onplay = function() {
        //Start drawing
        drawWave();
    };

    //On pause
    audioElement.onpause = function() {
        //Stop drawing
        cancelAnimationFrame(animation);
    };

    //On ended
    audioElement.onended = function() {
        //Stop drawing
        cancelAnimationFrame(animation);

        //Clear previous drawing
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        //Clear previous x and y values
        drawX = 0;
        drawY = 0;

        //Prevent audio from looping (you can remove this if you want it to loop)
        audioElement.pause();
    };
};

//Our drawing method
function drawWave() {

    //Current time (seconds)
    var currentTime = audioElement.currentTime;

    // Copy frequency data to frequencyData array.
    analyser.getByteFrequencyData(frequencyData);

    //Total loudness of all frequencies in frequencyData
    var totalLoudness = 0;
    for(var i = 0; i < frequencyData.length; i++) {
        totalLoudness += frequencyData[i];
    }

    //Average loudness of all frequencies in frequencyData
    var averageLoudness = totalLoudness / frequencyData.length;

    //Get the previous x axis value
    var previousDrawX = drawX;

    //Scale of progress in song (from 0 to 1)
    drawX =  currentTime / duration;
    //Multiply with canvas width to get x axis value
    drawX *= canvas.width;

    //Get the previous y axis value
    var previousDrawY = drawY;

    //Scale of average loudness from (0 to 1), frequency loudness scale is (0 to 255)
    drawY = averageLoudness / 255;
    //Multiply with canvas height to get scale from (0 to canvas height)
    drawY *= canvas.height;
    //Since a canvas y axis is inverted from a normal y axis we have to flip it to get a normal y axis value
    drawY = canvas.height - drawY;

    //Draw line
    ctx.beginPath();
    ctx.moveTo(previousDrawX, previousDrawY);
    ctx.lineTo(drawX, drawY);
    ctx.stroke();

    //Animate
    animation = requestAnimationFrame(drawWave);
}

这里是 CSS

figure {
    margin: 0;
}

但它对我不起作用,并且在控制台上也显示一些错误页面上它只显示按钮但不显示音频可视化和音频完美地工作这就是为什么我使用图形块来测试它.....

请看我附上的截图。

Console Error and Output

我还尝试了其他已经在 Stackoverflow 上讨论过的帖子,但没有发现任何像上面那样相关且简单的帖子。

如果有人能帮我解决这个问题,我将不胜感激。

提前致谢

【问题讨论】:

  • 请添加您的代码。它使我们更容易看到可能出现的问题。查看错误,可能是您尝试在 DOM 完全加载之前播放音频,但现在有点猜测......
  • 我刚刚编辑了我的帖子
  • 在 onload 事件中添加你所有的 JavaScript 代码:$(window).on("load", function(){ /*你的代码在这里 */});
  • 现在错误是:AudioContext 不允许启动。它必须在页面上的用户手势之后恢复(或创建)。当我点击播放时发生新错误:MediaElementAudioSource 由于文件的CORS访问限制而输出零:///Users/keikss/Projects/audio-visual/bensound-perception.mp3
  • audiocontext 错误是一个新策略:developers.google.com/web/updates/2017/09/…。对于 CORS,这篇文章可能会有所帮助:stackoverflow.com/questions/31083704/…

标签: javascript html css


【解决方案1】:

错误表示你的JS代码找不到&lt;audio /&gt;元素。确保页面上有此元素,并使用实际元素的 ID 在 document.getElementById(...) 中引用它。

【讨论】:

  • 你还是有同样的问题,把你的js文件放在文档末尾再关闭body标签。
  • 已经试过了..还使用控制台cmets标签检查我的js是否工作,评论部分工作正常..
猜你喜欢
  • 2023-03-31
  • 1970-01-01
  • 2016-12-09
  • 2017-07-08
  • 2012-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多