最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - wavesurfer.js won't load local file - Stack Overflow

programmeradmin0浏览0评论

I have been working on an online application that allows the user to click through and manipulate mp3 files, and I'm trying to load local files from my puter into a wavesurfer object, but I keep getting this error in 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."

I've tried putting both the HTML and mp3 files in multiple different folders on multiple puters, but nothing seems to be working. Here is my code:

<body>
    <script src=".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(".mp3");
        var song = "clippedJaco.mp3";
        wavesurfer.load(song);
        wavesurfer.on('ready', function () {wavesurfer.play();});
    </script>
</body>

When adding the "MediaElement" backend, the mp3 loads, but no waveform is generated. Any help is greatly appreciated, thanks!

I have been working on an online application that allows the user to click through and manipulate mp3 files, and I'm trying to load local files from my puter into a wavesurfer object, but I keep getting this error in 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."

I've tried putting both the HTML and mp3 files in multiple different folders on multiple puters, but nothing seems to be working. Here is my code:

<body>
    <script src="https://cdnjs.cloudflare./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/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>

When adding the "MediaElement" backend, the mp3 loads, but no waveform is generated. Any help is greatly appreciated, thanks!

Share Improve this question edited Sep 4, 2019 at 16:44 Ishara Amarasekera 1,4492 gold badges21 silver badges37 bronze badges asked Mar 8, 2017 at 17:12 Mitchell DalzinMitchell Dalzin 511 silver badge4 bronze badges 5
  • Possible duplicate of "Cross origin requests are only supported for HTTP." error when loading a local file – Scott Stensland Commented Mar 8, 2017 at 19:32
  • duplicate question stackoverflow./a/21608670/147175 ... just cd into dir where your html file lives and issue python mand ... python -m SimpleHTTPServer .... then view links in browser at localhost:8000 – Scott Stensland Commented Mar 8, 2017 at 19:34
  • I ended up getting it to work by creating a blob file url once I realized loading directly from file wouldn't work at all. Thank you so much for the suggestions! – Mitchell Dalzin Commented Mar 9, 2017 at 17:08
  • Also see stackoverflow./questions/31310904/… – mspae Commented Aug 13, 2017 at 15:53
  • @MitchellDalzin can you please show your answer – Ashok Shah Commented Sep 12, 2017 at 16:58
Add a ment  | 

3 Answers 3

Reset to default 3

Since you cannot load resources from external origins, for security reasons, this can be annoying if you are trying to load from a non HTTP source. And sometimes it is not possible to put a mini HTTP server or modify browser flags (don't do this, it's dangerous) to get around this.

I've just stumbled into this issue recently and found a nice solution on a blog (Author Carlos Delgado) which loads the local resources with a HTML input element and uses a JS blob filereader to pass these to the wavesurfer code. Here is the non-jquery code, worked for me perfectly:

    // 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./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" />

As I understand, this is because for security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. This means that a web application using XMLHttpRequest and the Fetch APIs can only request HTTP resources from the same origin the application was loaded from, unless the response from the other origin includes the right CORS headers.

Source: Cross-Origin Resource Sharing (CORS)

One way to resolve this issue is to host your web application in the localhost. You can use this to get started. Then inside index.html file call the wavesurfer.js and create a container where the waveform is to appear.

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./wavesurfer.js"></script> -->

<head>
  <title>Test Website</title>
</head>

<body>
  <!-- Adding wavesurfer.js script -->
  <script src="https://cdnjs.cloudflare./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>

Then add a script to handle wavesurfer instance. In my case it was 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 i.e when wavesurfer ready event
wavesurfer.on('ready', function() {
  wavesurfer.play();
});

This way I didn't have any trouble in loading a local audio file to wavesurfer. Hope this helps.

This code snippet will work for load audio file from your local folder.

//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'
});

//This is the event you play the wavesurver instance i.e when wavesurfer ready event
wavesurfer.on('ready', function() {
  wavesurfer.play();
});

//Loading the audio file you want to play
const audio = new Audio("assets/audio.mp3") // assets folder in root project folder for Vanilla JS
//const audio = new Audio("./assets/audio.mp3") // assets folder in src folder for React JS
wavesurfer.load(audio);

// You can also load wav files if you want
//const audio = new Audio("assets/audio.wav") 

发布评论

评论列表(0)

  1. 暂无评论