Search code examples
javascriptaudiocontrolsblobsrc

Put javascript blob variable in src of audio


In my javascript code I create a url from my audio blob

var blobUrl = URL.createObjectURL(blob);

I then have an audio controller. How do I put the blobUrl variable into the src = ?

<audio controls="controls">
<source src= blobUrl type="audio/mp3">
</audio>

Solution

  • You need to get the source element and set its src property.

    Lets get the element using the basic js DOM API.

    var srcElement = document.getElementsByTagName("source")[0]; // Assuming there's only one
    

    Now lets set the src property using

    srcElement.src = blobUrl; or srcElement.setAttribute("src", blobUrl); or jquery's element.attr() method if you get the element using a jquery selector.