gpt4 book ai didi

javascript - wavesurfer.js 不会加载本地文件

转载 作者:行者123 更新时间:2023-11-28 02:43:12 30 4
gpt4 key购买 nike

我一直在开发一个允许用户点击并操作 mp3 文件的在线应用程序,我正在尝试将本地文件从我的计算机加载到 wavesurfer 对象中,但我在 chrome 中不断收到此错误:

"Access to XMLHttpRequest at 'file:///local/file/path/to/audio/files/some.mp3' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https."

我试过将 HTML 和 mp3 文件放在多台计算机上的多个不同文件夹中,但似乎没有任何效果。这是我的代码:

<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/wavesurfer.js/1.2.3/wavesurfer.min.js"></script>
<div id="waveform"></div>

<script>
var wavesurfer = WaveSurfer.create({
container: '#waveform',
waveColor: 'darkorange',
progressColor: 'blue',
height: 64,
backend: 'MediaElement'
});


//setRequestHeader('Origin', document.domain);
//wavesurfer.load("http://ia902606.us.archive.org/35/items/shortpoetry_047_librivox/song_cjrg_teasdale_64kb.mp3");
var song = "clippedJaco.mp3";
wavesurfer.load(song);
wavesurfer.on('ready', function () {wavesurfer.play();});
</script>
</body>

添加“MediaElement”后端时,会加载 mp3,但不会生成波形。非常感谢任何帮助,谢谢!

最佳答案

由于您无法从外部源加载资源,出于安全原因,如果您尝试从非 HTTP 源加载,这可能会很烦人。有时无法通过放置迷你 HTTP 服务器或修改浏览器标志(不要这样做,这很危险)来解决这个问题。

我最近偶然发现了这个问题,并在博客(作者 Carlos Delgado)上找到了一个很好的解决方案,它使用 HTML 输入元素加载本地资源,并使用 JS blob 文件读取器将这些资源传递给 wavesurfer 代码。这是非 jquery 代码,非常适合我:

    // JS:Initialize WaveSurfer
var wavesurfer = WaveSurfer.create({
container: '#waveform',
});

// Once the user loads a file in the fileinput, the file should be loaded into waveform
document.getElementById("fileinput").addEventListener('change', function(e){
var file = this.files[0];

if (file) {
var reader = new FileReader();

reader.onload = function (evt) {
// Create a Blob providing as first argument a typed array with the file buffer
var blob = new window.Blob([new Uint8Array(evt.target.result)]);

// Load the blob into Wavesurfer
wavesurfer.loadBlob(blob);
};

reader.onerror = function (evt) {
console.error("An error ocurred reading the file: ", evt);
};

// Read File as an ArrayBuffer
reader.readAsArrayBuffer(file);
}
}, false);
<script src="https://unpkg.com/wavesurfer.js"></script>
<!-- HTML: Initialize a div for WaveSurfer -->
<div id="waveform"></div>

<!-- Add a file input where the user should drag the file to load into WaveForm -->
<input type="file" id="fileinput" />

关于javascript - wavesurfer.js 不会加载本地文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42677632/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com