Open LePhenix47 opened 1 year ago
There is another way to convert a file into readable data with the URL.createObjectUrl([File object])
, the only difference being that unlike the base₆₄ string, the URL generated is a temporary Binary large object
URL and will be invalid once the user closes the tab
In other words, the lifespan of a blob URL is tied to the document or web page that created it.
Here's how
1. Recovering the file
First we must get the file that uploaded by the user in an asynchronous function, here's how with both an input and a dropzone:
2. Checking its type
We'll need to perform a type check if needed to check if the audio uploaded is indeed an audio file:
3. Converting it to a base₆₄ string
Browsers cannot read binary data for security reasons, they only read text, so they must be converted into a base 64 string thus for that we'll create a function that returns a promise where a file reader will read it as text:
4. Creating or adding the audio string
We've converted our binary file into a base₆₄ string, now all we need is to create the audio element :
Or change it's
src
attribute to the string if there was already an<audio>
element:5. (Optional) Authorize the audio context
If we need the audio context to create visual effects with a
<canvas>
elementIf you create an AudioContext before the document receives any user interaction, it will be created in a "suspended" state, which means you'll need to call the
resume()
method after the user interacts with the page in order to activate it. Source: https://developer.chrome.com/blog/autoplay/#web-audioSo we'll need to create a function that will resume the audio context when the user makes a gesture, such as a button click: