Search code examples
javascripturlaudiofileapi

Passing createObjectURL


I want to pass the address created by window.URL.createObjectURL(file) to dancer.js but I get GET blob:http%3A//localhost/b847c5cd-aaa7-4ce0-8ff8-c13c6fc3505a.mp3 404 (Not Found).

I manage to create an audio element with a file selected through a file input, but dancer.js simply does not find the file... any ideas? (Below how i pass the ObjectURL)

    $(document).ready(function(){
    $("#submit").click(function(){
        var file = document.getElementById("file").files[0];
        $('body').append('<audio id="audio" controls="controls"></audio>');
        $('#audio').append('<source src='+window.URL.createObjectURL(file)+' type=audio/mpeg />')
        $('body').append('<a href='+window.URL.createObjectURL(file)+'>link</a>')
        dancer(window.URL.createObjectURL(file));
    })
})

Solution

  • Looking at the dancer.js readme it looks like the load method will take either a reference to a <audio> element or a configuration object that specifies the source: {scr: varHoldingFileURL}. Since you are already creating a <audio> element for your file I'd just pass that to dancer:

    $(document).ready(function() {
        var dancer = new Dancer(),
            fileURL;
    
        $("#submit").click(function(){
                var audioElement,
                    file = document.getElementById("file").files[0];
    
                fileURL = window.URL.createObjectURL(file);
    
                // remove any preexisting instances of the audio tag
                $('#audio').remove();
    
                // Revoke any previously used file URL so it doesn't
                // take up memory anymore.
                window.URL.revokeObjectURL(fileURL);
    
                $('body').append('<audio id="audio" controls="controls"></audio>');
                $('#audio').append('<source src='+ fileURL +' type=audio/mpeg />')
                $('body').append('<a href=' + fileURL +'>link</a>')
    
                // get a reference to the audio element we created
                audioElement = $('#audio')[0];
    
                dancer.load(audioElement);
        })
    });