You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AudioContext实现JavaScript音频可视化无显示问题求助

问题描述

跟随教程学习用AudioContext实现JavaScript音频可视化,Mac系统VSCode开发,Chrome浏览器加载页面后音频可正常播放,但可视化条无显示,代码和教程一致,请求排查问题。

代码问题排查与修复

以下是导致可视化失效的关键问题及修复方案:

  • canvas高度设置错误:原代码中canvas.height = canvas.innerHeight;是错误的,canvas元素没有innerHeight属性,应改为window.innerHeight,与宽度设置逻辑统一。
  • clearRect参数拼写错误:动画函数里的canvas.wdth是笔误,正确应为canvas.width,该错误导致画布无法被正确清空,可视化内容无法更新渲染。
  • 变量作用域冗余:全局声明了let analyser;,但点击事件内又用const analyser重新声明,虽不直接影响功能,但会造成变量遮蔽,建议统一使用全局变量。

修复后的完整JavaScript代码:

const container = document.getElementById('container');
const canvas = document.getElementById('canvas1');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight; // 修复高度设置错误
const ctx = canvas.getContext('2d');
let audioSource;
let analyser;

container.addEventListener('click', function(){
    let audio1 = new Audio();
    audio1.src = 'Hall.mp3';
    const audioContext = new AudioContext();
    audioSource = audioContext.createMediaElementSource(audio1);
    analyser = audioContext.createAnalyser(); // 统一使用全局analyser变量
    audioSource.connect(analyser);
    analyser.connect(audioContext.destination);
    analyser.fftSize = 2048;
    const bufferLength = analyser.frequencyBinCount;
    const dataArray = new Uint8Array(bufferLength);

    const barWidth = canvas.width/bufferLength;
    let barHeight;
    let x;

    function animate(){
        x = 0;
        ctx.clearRect(0, 0, canvas.width, canvas.height); // 修复拼写错误
        analyser.getByteFrequencyData(dataArray);
        for (let i = 0; i < bufferLength; i++){
            barHeight = dataArray[i];
            ctx.fillStyle = 'white';
            ctx.fillRect(x, canvas.height - barHeight, barWidth, barHeight);
            x += barWidth;
        }
        requestAnimationFrame(animate);
    };
    animate();
    audio1.play(); // 调整播放时机,确保音频流已连接分析器
});

额外提示:

  • 若本地加载音频出现跨域问题,可使用VSCode的Live Server插件启动本地服务,避免浏览器的跨域限制。
  • 可打开Chrome开发者工具(F12)的Console面板,查看是否有其他报错信息,辅助排查问题。

内容的提问来源于stack exchange,提问作者SlowSSD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 04:45:15