Can howler.js play audio from a blob URL?
Yes, howler.js can play audio from a blob URL, but it requires a specific configuration step to work correctly. Because blob URLs do not contain standard file extensions, howler.js cannot automatically detect the audio format, which will cause playback to fail unless the format is explicitly defined. This article explains how to properly load and play blob URLs using howler.js.
Why Blob URLs Require Special Handling
Typically, howler.js looks at the file extension at the end of a URL
(such as .mp3 or .wav) to determine how to
decode and play the audio. A blob URL typically looks like this:
blob:http://localhost:3000/d3b07384-d113-462c-a550-2c2c1a1a72d7
Since there is no file extension in this string, howler.js cannot
determine the codec to use. To bypass this, you must use the
format property when initializing your Howl
instance.
How to Play a Blob URL
To play a blob URL, generate the object URL from your audio Blob and
pass it to the src array, while explicitly stating the
audio format (e.g., 'mp3', 'wav',
'ogg') in the format array.
Here is a practical code example:
// Assume you have an audio Blob (e.g., from a microphone recording or a fetch request)
const audioBlob = new Blob([/* audio data */], { type: 'audio/mp3' });
// Create a local URL pointing to the Blob
const blobUrl = URL.createObjectURL(audioBlob);
// Initialize Howler with the blob URL and the explicit format
const sound = new Howl({
src: [blobUrl],
format: ['mp3'], // This is required for blob URLs to work
html5: true // Recommended for larger audio files to stream them
});
// Play the audio
sound.play();Best Practices
- Memory Cleanup: Blob URLs remain in the browser’s
memory until the page is closed or unloaded. To prevent memory leaks,
free up the memory by calling
URL.revokeObjectURL(blobUrl)once the sound has finished loading or is no longer needed. - Format Accuracy: Ensure that the string you pass to
the
formatarray matches the actual MIME type of the audio data stored inside the Blob.