Mit*_*zin 5 html javascript audio wavesurfer.js
我一直在开发一个在线应用程序,允许用户点击并操作 mp3 文件,并且我试图将本地文件从我的计算机加载到 Wavesurfer 对象中,但我在 chrome 中不断收到此错误:
“从源“null”访问“file:///local/file/path/to/audio/files/some.mp3”处的 XMLHttpRequest 已被 CORS 策略阻止:跨源请求仅支持协议方案:http 、数据、chrome、chrome 扩展、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>
Run Code Online (Sandbox Code Playgroud)
添加“MediaElement”后端时,会加载 mp3,但不会生成波形。非常感谢任何帮助,谢谢!
据我了解,这是因为出于安全原因,浏览器限制从脚本内发起的跨源 HTTP 请求。这意味着使用 XMLHttpRequest 和 Fetch API 的 Web 应用程序只能从加载应用程序的同一源请求 HTTP 资源,除非来自其他源的响应包含正确的 CORS 标头。
来源:跨源资源共享(CORS)
解决此问题的一种方法是将 Web 应用程序托管在本地主机中。您可以使用它来开始。然后在index.html文件内调用wavesurfer.js并创建一个要显示波形的容器。
索引.html
<!doctype html>
<!-- You can use this link as well to call wavesurfer.js. This is what's given on their updated documentation-->
<!-- <script src="https://unpkg.com/wavesurfer.js"></script> -->
<head>
<title>Test Website</title>
</head>
<body>
<!-- Adding wavesurfer.js script -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/wavesurfer.js/1.2.3/wavesurfer.min.js"></script>
<h1>Wavesurfer Test</h1>
<!-- !-- Create a container where the waveform is to appear-->
<div id="waveform"></div>
<script src="script/main.js" defer="defer"></script>
<script src="script/test.js"></script>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
然后添加一个脚本来处理wavesurfer实例。就我而言是test.js
测试.js
//Creating a wavesurfer instance, passing the container selector along with some options like progress color and wave color
var wavesurfer = WaveSurfer.create({
container: '#waveform',
waveColor: 'violet',
progressColor: 'purple'
});
//Loading the audio file you want to play
wavesurfer.load('audio/LOVE_s.mp3');
// You can also load wav files if you want
//wavesurfer.load('audio/songaudio.wav');
//This is the event you play the wavesurver instance i.e when wavesurfer ready event
wavesurfer.on('ready', function() {
wavesurfer.play();
});Run Code Online (Sandbox Code Playgroud)
这样我在将本地音频文件加载到wavesurfer 时就没有任何问题了。希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
6385 次 |
| 最近记录: |