javascript - 由于 CORS 访问限制本地 mp3 文件,MediaElementAudioSource 输出零

标签 javascript html cors html5-audio

我有以下 html 页面,我试图展示一个类来演示带有本地存储的 mp3 的音频可视化工具:

<!doctype html>
<html>
<head>
    <header name = "Access-Control-Allow-Origin" value = "*" /> 
    <style type = "text/css">
            div#mp3_player{ width: 500px; height: 60px; background: #000; padding: 5px; margin: 50px auto;}
        div#mp3_player > div > audio{ width: 500px; background: #000; float: left; }
        div#mp3_player > canvas { width: 500px; height: 30px; background: #002D3C; float: left;}
    </style>
    <script>
    //create new instance of audio 
    var audio = new Audio();
    audio.src = 'C:/Users/Adam/Desktop/1901.m4a';
    audio.controls = true;
    audio.loop = true;
    audio.autoplay = true;

    var canvas, ctx, source, context, analyser, fbc_array, bars, bar_x, bar_width, bar_height;

    window.addEventListener("load", initMp3Player, false);


    function frameLooper(){
        window.webkitRequestAnimationFrame(frameLooper);
        fbc_array = new Uint8Array(analyser.frequencyBinCount);
        analyser.getByteFrequencyData(fbc_array);
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = "#00CCFF";
        bars = 100;
        for (var i = 0; i < bars; i++){
            bar_x = i * 3;
            bar_width = 2;
            bar_height = -(fbc_array[i]/2);
            ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
        }
    }

    function initMp3Player(){
        document.getElementById('audio_box').appendChild(audio);
        context = new AudioContext();
        analyser = context.createAnalyser();
        canvas = document.getElementById('analyser_render');
        ctx = canvas.getContext('2d');
        source = context.createMediaElementSource(audio);
        source.connect(analyser);
        analyser.connect(context.destination);
        frameLooper();
    }

    </script>

</head>

<body>
    <div id = "mp3_player">
        <div id = "audio_box"></div>
        <canvas id = "analyser_render"></canvas>
    </div>

</body>

在使用脚本标签中的所有代码之前,我已经让 mp3 文件自动播放,不包括该行下面的代码

audio.autoplay = true;

但是当我包含 frameLooper 函数时,我收到消息“由于 CORS 访问限制,MediaElementAudioSource 输出零。”因为它是一个本地文件,所以有什么办法可以避免这种情况吗?

最佳答案

在初始化 Audio 对象之后,添加以下内容:

audio.crossOrigin = "anonymous";

这应该可以防止 CORS 访问限制。

关于javascript - 由于 CORS 访问限制本地 mp3 文件,MediaElementAudioSource 输出零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31308679/

相关文章:

javascript - 如何制作包含多个文件的 requirejs 模块

javascript - 如何从函数中的函数返回 deferred.resolve()

javascript - 在事件类中使用空白空间

html - 我应该为歌曲列表使用 html 表格还是 div?

html - 添加空格分隔符以仅输入类型号

javascript - HTML/CSS/JS/JQUERY : Make objects fixed even if the window is resized

html - 静态文件未加载 [DJANGO]

cors - Cloudflare 页面 - Cloudflare Workers

html - 浏览器 Canvas CORS 支持跨域加载图像操作

node.js - 通过 Observable 从 Angular 向 NodeJS 发送 POST 请求