This is a repost of an article I wrote early on in this blog's history. Since there continue to be frequent questions on the MATLAB newsgroup regarding processing a set of files, I thought it would be worthwhile recapping this post.
I should start a clean workspace and with no WAV-files in my blog publishing directory.
clear all delete *.wav
Suppose I want to convert sounds stored in MATLAB MAT-files to files saved in WAV format for Windows. Without explictly hardcoding in the filenames, here's a way to proceed.
matfiles = dir(fullfile(matlabroot,'toolbox','matlab','audiovideo','*.mat'))
matfiles = 6x1 struct array with fields: name date bytes isdir datenum
We can see from the length of matfiles that I have 6 MAT-files.
Name Size Bytes Class Attributes Fs 1x1 8 double matfiles 6x1 2576 struct y 13129x1 105032 double
Loading the data places the MAT-file contents into a structure from which I can extract the information I need and write it back out. The sound files that MATLAB ships with store the data in y and the sampling frequency in Fs. Let's look at the first signal.
N = length(y); plot((1:N)/(N*Fs),y), title(matfiles(1).name(1:end-4))
for ind = 2:length(matfiles) data = load(matfiles(ind).name); wavwrite(data.y,data.Fs,matfiles(ind).name(1:end-4)); end
Warning: Data clipped during write to file:gong Warning: Data clipped during write to file:splat Warning: Data clipped during write to file:train
gong.wav laughter.wav train.wav handel.wav splat.wav
I'll double-check the last file I just read in and wrote out. ind is still set despite no longer being in the for loop. Let's check both the frequencies and the signals themselves.
[ywav, Fswav] = wavread(matfiles(ind).name(1:end-4)); eqFreqs = isequal(Fswav, data.Fs) datadiff = norm(ywav-data.y)
eqFreqs = 1 datadiff = 0.0010
The data stored in the WAV-file is NOT exactly the same as that stored in the MAT-file. Reading the help for wavwrite gives some insight; the data in the WAV-file, by default, is stored as 16-bit data vs. MATLAB's standard 64-bit double.
Does it confuse people here that I don't worry about vectorization? Any other thoughts on this topic?
要发表评论，请点击 此处 登录到您的 MathWorks 帐户或创建一个新帐户。