4-5 Writing Audio Files

We can write ".wav" audio files by using the MATLAB command "wavwrite". The command format is
wavwrite(y, fs, nbits, waveFile);
where "y" is the audio data, "fs" is the sample rate, "nbits" is the bit resolution, and "waveFile" is the .wav file to be written to. For instance, we can follow the next example to write my recording to a file "test.wav".

Example 1: matlab4asp/wavWrite01.mfs=11025; % Sampling rate (取樣頻率) duration=2; % Recording duration (錄音時間) waveFile='test.wav'; % Wav file to be saved (欲儲存的 wav 檔案) fprintf('Press any key to start %g seconds of recording...', duration); pause fprintf('Recording...'); y=wavrecord(duration*fs, fs); fprintf('Finished recording.\n'); fprintf('Press any key to save the sound data to %s...', waveFile); pause nbits=8; % Bit resolution (每點的解析度為 8-bit) wavwrite(y, fs, nbits, waveFile); fprintf('Finished writing %s\n', waveFile); fprintf('Press any key to play %s...\n', waveFile); dos(['start ', waveFile]); % Start the application for .wav file (開啟與 wav 檔案對應的應用程式)

(You need to execute the above example in order to experience the recording and the file saving.) In this example, we store the audio data in the data type 'uint8' and write the data to the wave file "test.wav". We then invoke the corresponding application for ".wav" for the playback of the file. Since the variable "y" for the command "wavwrite" should be a double within the range [-1, 1], we need to do some conversion if the recorded data is in other data types, such as 'single', 'int16', or 'uint8'. Here is the table for conversion.

Data types of "y"How to convert it to 'double' within [-1, 1]
doubleNo conversion needed
singley = double(y);
int16 y = double(y)/32768;
uint8 y = (double(y)-128)/128;
MATLAB can also write other audio files, such as '.au', which is the audio files used in NeXT/Sun workstations. The corresponding command is "auwrite". Please type "help auwrite" within the MATLAB command windows for more information on using this command.

Hint
If you want to do audio signal processing with MATLAB exclusively, you can save your audio data using "save" command to save them into .mat files. You can then load these mat files using the command "load" directly.


Audio Signal Processing and Recognition (音訊處理與辨識)