繁体   English   中英

在客户端和文件:///中播放带有音频波形的mp3

[英]Play mp3 with Audio Waves in client side and file:///

我正在尝试使用waveurfer-js加载音频波

这很好用,但对我来说挑战是从chrome中的file:///协议加载。

从本地加载时出现以下错误。

无法加载文件:///Users/ashokshah/audioWaveTest/audio.wav:仅协议方案支持跨源请求:http,数据,chrome,chrome扩展名,https。

 var wavesurfer = WaveSurfer.create({ container: '#waveform', waveColor: 'violet', progressColor: 'purple' }); window.onload = function () { wavesurfer.load('audio.wav'); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/wavesurfer.js/1.4.0/wavesurfer.min.js"></script> <div id="waveform"></div> <button onClick="wavesurfer.play()">Play</button> 

请帮助我实现通过File:///协议在Chrome中显示音频波。

据我了解,这是因为出于安全原因,浏览器限制了从脚本内部发起的跨域HTTP请求。 这意味着使用XMLHttpRequest和Fetch API的Web应用程序只能从加载该应用程序的同一来源请求HTTP资源,除非来自其他来源的响应包括正确的CORS标头。

来源: 跨域资源共享(CORS)

解决此问题的一种方法是将Web应用程序托管在localhost中。 您可以使用开始。 然后在index.html文件中调用wavesurfer.js并创建一个要显示波形的容器。

index.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> 

然后添加一个脚本来处理waveurfer实例。 就我而言,这是test.js

test.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 ie when wavesurfer ready event wavesurfer.on('ready', function() { wavesurfer.play(); }); 

这样,我就可以轻松地将本地音频文件加载到waveurfer。 希望这可以帮助。

我找到了一种解决方案,可通过将音频文件的blob创建到JavaScript变量中并使用它而不是音频路径来绕过跨域策略。

您可以使用https://www.npmjs.com/package/stream-to-blob或使用许多其他选项来创建音频文件的blob。

无论您获得什么文本内容,都只需将其存储到JavaScript变量中,然后使用该变量而不是音频路径来加载wave冲浪者。 给出以下示例:

var myAudio = "data:audio/x-wav;base64,UklGR..."; // enter complete blob data. I have removed it since it was not allowing to paste me completely
waveSurfer.load(myAudio);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM