首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >由于CORS访问限制本地mp3文件,MediaElementAudioSource输出为零

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

Stack Overflow用户
提问于 2015-07-09 13:13:53
回答 1查看 21.1K关注 0票数 33

我有下面的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输出零”。既然它是一个本地文件,有没有什么办法可以绕过它?

EN

回答 1

Stack Overflow用户

发布于 2015-09-11 10:05:52

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

audio.crossOrigin = "anonymous";

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

票数 56
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31308679

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档