I'm working on an app built with electron, it should work with wavesurfer.js to display a waveform representing the audio file. However, I'm having trouble opening the file using the fs
module and pushing the file content to wavesurfer via a Blob. The file loads and everything seems to work but when decoding wavesurfer says Error decoding audiobuffer
.
Two things I thought maybe could influence this:
fs.readFile
function takes an encoding as second parametertype
propertyHowever, until now both approaches have failed to fix the problem.
I hope somebody has a solution. (Could also be the fs.readFile
function is entirely the wrong way to go and there's a much better way; I'm just looking for a relatively performant way of opening a file, any help is appreciated) Cheers!
Here's the code …
(I'm leaving out all the electron boilerplate, you can get it easily by doing git clone https://github.com/sindresorhus/electron-boilerplate/
) – Include a script tag to main.js
in the index.html
, add a div with the id wave-area
somewhere in the html and add a script tag to the the wavesurfer.js library. Also you will need a local copy of the demo wav-file.
Then in the main.js
file …
var fs = require('fs');
var wavesurfer = Object.create(WaveSurfer);
wavesurfer.init({
container: '#wave-area'
});
fs.readFile('/path/to/demo.wav', function(err, data) {
if (data && !err) {
console.log('has data and no error!');
}
var file = new window.Blob([data]);
wavesurfer.loadBlob(file);
}
wavesurfer.on('loading', function(e) {
console.log('loading', e);
});
wavesurfer.on('error', function(err) {
console.log(err);
});
I finally found the solution! The blob which is passed to wavesurfer through the loadBlob
method needs to transformed into an Uint8Array
The working code looks like this
fs.readFile('/path/to/demo.wav', function(err, buffer) {
// …
var blob = new window.Blob([new Uint8Array(buffer)]);
wavesurfer.loadBlob(blob);
}