Skip to content Skip to sidebar Skip to footer

Html5 Audio Player Drag And Drop

I'm implementing audio player in html5, which has drag-drop option for load and play mp3 files, but I have problem with plaing the file. When the file is dropped on the area, I can

Solution 1:

Instead of using the absolute path to use as an src-attribute on an audio element, I suggest you read the contents of the file(s) and use the webAudio API for decoding the audio data.

Here is a working example for playing the dropped file immediately. But you can just save the buffer for later playback.

var context = newAudioContext()

window.addEventListener('load', function() {
    var dropzone = document.querySelector('#dropzone');
    dropzone.addEventListener('drop', handleDrop, false)
    dropzone.addEventListener('dragover', handleDragOver, false)
})

var handleDragOver = function(e) {
    e.preventDefault()
    e.stopPropagation()
}

var handleDrop = function(e) {
    e.preventDefault()
    e.stopPropagation()

    var files = e.dataTransfer.filesfor (var i = 0; i < files.length; i++) {
        var file = files[i]
        var reader = newFileReader()
        reader.addEventListener('load', function(e) {
            var data = e.target.result
            context.decodeAudioData(data, function(buffer) {
                playSound(buffer)
            })
        })
        reader.readAsArrayBuffer(file)
    }
}

var playSound = function(buffer) {
    var source = context.createBufferSource()
    source.buffer = buffer
    source.connect(context.destination)
    source.start(0)
}

Solution 2:

You can disable the web security of the browser. In the terminal, cd to the application and type "--disable-web-security" without the quotes.

Solution 3:

I think you are forgetting to load the audio before playing it. I always forget this when retrieving audio files to play.

document.getElementsByTagName("audio")[0].load();
document.getElementsByTagName("audio")[0].play();

Post a Comment for "Html5 Audio Player Drag And Drop"