I'm using the getUserMedia API to allow a user to record a short Audio clip on the client. After finishing the recording, I initialize a FileReader, create a Blob from all the Audio chunks, and read the reader of the blob as a DataURL. That gets appended as Text to a webform that's then sent to a Rails5 API, where I'm having a very difficult time converting the Binary Audio into a working .mp3 file.
Here is what the code looks like:
When the recorder goes inactive, the chunks are collected and used to instantiate a new Blob with the type 'audio/mpeg'.
var chunks = [];
if (recorder.state == 'inactive') {
var blob = new Blob(chunks, { type: 'audio/mpeg' });
App.mediaStream.encodeBase64(blob);
}
The Blob is then passed to a function that creates a base64 encoded DataURL.
encodeBase64: function(blob) {
var reader = new FileReader();
reader.onloadend = function() {
App.mediaStream.appendToForm(reader.result);
};
reader.readAsDataURL(blob);
},
The result from the reader is a dataURL that follows this pattern, data:[type];base64,[data] - so it's a String that looks like:
"data:audio/mpeg;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQRChYECGFOAZwH/////////FUmpZpkq17GDD0JATYCGQ2hyb21lV0GGQ2hyb21lFlSua7uuudeBAXPFh+bmBbc......."
I'm appending this DataURL to a form, that sends it to my Rails 5 API along with some other data. Here is where I'm running into trouble. On the server side, I have a ruby method that parses the dataURL, and writes it to a file as so:
def binary_to_audio_file(dataURL)
data = dataURL.split(',').last
filename = SecureRandom.hex
File.open("public/#{filename}.mp3", 'wb') do |f|
f.write Base64.decode64(data)
end
end
This is successfully creating a new file in the specified directory that has the decoded audio binary written to the file. That file can be opened by QuickTime, Itunes, or any other media play. It even plays for the same duration that the recording lasted. HOWEVER, there is NO sound.
I promise my speakers are not turned off... any hints?