3

is it possible to convert a wav string to an html5 blob ?

( I'm not looking for a crossbrowser compatible solution, I just need it to work in Chrome ).

wavString = "RIFF  WAVEfmt D¬Xdata ¦®µ¼ÃÊÐÖÜáæêïòõøúüýþþþþüûøöóïëçâÜ×ÑËĽ¶¯§ xph`YQJC<5/~)~#~~~~~~  ~~~~~~~~~~~~~~~~~~!~'~,~3~9~@~GNV^emu}¥¬´»ÂÈÏÕÛàåéîñõøúüýþþþþýûùöóðìèãÞØÒÌÅ¿¸°©¡zrjb~Z~S~K~D~=~6~0~*~$}}}}}
}.....a lot of ugly chars.....";

I can convert the wavString to an html5 audio object and I can hear the wav sound if I play the sound:

var wave = new Audio('data:audio/wav;base64,' + btoa(wavString));
wave.controls = true;
document.body.appendChild(wave);

But I cannot create a wav blob from it, here is what I tried with no luck : ( I tried all combinations of type and blob vars ) :

var type = "audio/x-wav";
var type = "application/octet-stream";


var blob = new Blob([btoa(wavString)], {type: type});
var blob = new Blob(['data:audio/wav;base64,' + btoa(wavString)], {type: type});
var blob = new Blob([wavString], {type: type});

None of those works : they create blob, but I cannot save them to a server and listen to them as wav files. What I want to do is create a blob that I can export to a server as a wav file. Actually I can export a valid wav blob to a server, to the problem is really to convert this wavString to a valid wav blob.

ling
  • 9,545
  • 4
  • 52
  • 49

1 Answers1

9

Creating ArrayBuffer may work.

var wavString = "RIFF  WAVEfmt.....a lot of ugly chars.....";
var len = wavString.length;
var buf = new ArrayBuffer(len);
var view = new Uint8Array(buf);
for (var i = 0; i < len; i++) {
  view[i] = wavString.charCodeAt(i) & 0xff;
}
var blob = new Blob([view], {type: "audio/x-wav"});
kuu
  • 815
  • 1
  • 7
  • 16
  • I am able to get and play audio file from above logic, but audio file is completely corrupted, it is not same as original. What I am doing is, I am making an ajax request and on the response data, I am applying the above logic. – Shoib Mohammed A Oct 05 '15 at 10:36
  • 5
    Cool its working now, i have to set mime type to 'xhr.overrideMimeType( "text/plain; charset=x-user-defined" );' in beforeSend ajax method – Shoib Mohammed A Oct 05 '15 at 10:43
  • Hi Mohammed. I am facing a similar issue. can you look into my post? – Fernando May 13 '22 at 05:23
  • https://stackoverflow.com/questions/72223068/how-to-store-as-a-blob-the-audio-recoding-from-azure-api-speechsynthesizer-and-p – Fernando May 13 '22 at 05:24