0

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

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

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

加载文件失败:///Users/ashokshah/audioWaveTest/audio.wav:跨源请求仅支持协议方案:http、data、chrome、chrome-extension、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 中显示音频波。

4

2 回答 2

1

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

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

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

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);
于 2019-10-04T06:43:36.250 回答
0

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

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

解决此问题的一种方法是将 Web 应用程序托管在 localhost 中。您可以使用来开始。然后在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>

然后添加一个脚本来处理 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();
});

这样我在将本地音频文件加载到 wavesurfer 时没有任何问题。希望这可以帮助。

于 2019-09-04T16:30:14.107 回答