MATLAB: Convert Wav file to binary, send it through simulink and convert it back to wav

audiobinaryconvertMATLABsimulinkwav

Hi,
i want to convert a .wav file (16Bit, 44100Hz, stereo) to a binary stream file, than send it through simulink via "Binary File Reader", read the Output from "Binary File Writer" back into Matlab and convert it back to .wav to hear the result of my Reverb i build with simulink.
my steps so far:
wavdata = audioread("Closed-Hi-Hat-1.wav");
wavbinary = dec2bin( typecast( single(wavdata(:)), 'uint8'), 8 ) - '0';
now i have a wavdata variable with value:3247×2 double
and a wavbinary with 25976×8 double
fid = fopen('wav.bin', 'w');
fwrite(fid, wavbinary);
fclose(fid);
I now have the "wav.bin" file i can add to my "Binary File Reader" in simulink, when i send it through my "Reverb" i get a new "wav_reverb.bin" file.
next steps back in matlab:
fid = fopen('wav_reverb.bin');
A = fread(fid);
sound(A);
when i now play (A) it sounds not like the actual "Closed-Hi-Hat-1.wav" i sent through my "Reverb". It sounds very bad and scratchy. I think its a problem with the data types. And i dont know how to convert the "wav_reverb.bin" back to a .wav (maybe it sounds better than).
PS: i tried the example from Walter
>> wavbinary = dec2bin( typecast( single(wavdata(:)), 'uint8'), 8 ) - '0';
>> orig_size = size(wavdata);
>> data_class_to_use = 'int32';
>> SampleRate = 22100;
>> wavdata = reshape( typecast( uint8(bin2dec( char(wavbinary + '0') )), data_class_to_use ), orig_size );
>> audiowrite('FileNameGoesHer33e.wav', wavdata, SampleRate)
but the new audiofile sounds also scratchy and bad.
I hope anyone can help me
thanks
LK

Best Answer

I'm not entirely clear why you're jumping through so many hoops, but it looks like there's a misunderstanding. As far as I can tell (I don't have the required toolbox) a binary file reader is not intended to read streams of 0 and 1. It's intended to read streams of bytes as opposed to streams of characters. At least that's the common usage of binary file.
Sure, if you reconstruct the original data from your stream of 0 and 1 you should get back the same data but that's extremely wasteful. You start with double data = 8 bytes per samples, which you downcast to single by reducing the precision = 4 bytes per sample = 32 bits per sample. You then convert extract each bit and store each as double = 8 bytes per bit = 256 bytes per sample. So you've gone from having original data that takes 8 bytes per sample to slightly less precise data that takes 32 times more space.
You could just save the double wavdata into a file
fid = fopen('wav.bin', 'w');
fwrite(fid, wavdata, 'double');
fclose(fid);
and read that directly with the Binary File Reader.
Related Question