annotate toolboxes/bioakustik_tools/sp/seq_wavwrite.m @ 0:cc4b1211e677 tip

initial commit to HG from Changeset: 646 (e263d8a21543) added further path and more save "camirversion.m"
author Daniel Wolff
date Fri, 19 Aug 2016 13:07:06 +0200
parents
children
rev   line source
Daniel@0 1 function seq_wavwrite(in_files,wavefile,varargin)
Daniel@0 2 % Combines wav-data from folder or specific files in one file.
Daniel@0 3 %
Daniel@0 4 % seq_wavwrite(path_string,wavefile) combines all .wav files in
Daniel@0 5 % path_string in the file wavefile.
Daniel@0 6 % i.e.: seq_wavwrite('C:\wav\','C:\combined.wav')
Daniel@0 7 %
Daniel@0 8 % The file format will depend on the first file processed, the other
Daniel@0 9 % files will be transfered to this format by resampling, dithering and
Daniel@0 10 % channel repetition/rejection. You may use some of the extra-options 'Fs','nbits'
Daniel@0 11 % or 'channels' to override these settings.
Daniel@0 12 % i.e.: seq_wavwrite('C:\wav\','C:\combined.wav','Fs',44100,'nbits',16,'channels',1)
Daniel@0 13 % will produce a mono file with 44.1 kHz samle rate and 16bits per sample
Daniel@0 14 %
Daniel@0 15 % seq_wavwrite(files_cellarray,wavefile) only combines the files specified
Daniel@0 16 % in files_cellarray.
Daniel@0 17 % i.e.: files={'C:\wav\test1.wav','C:\other_wav\test2.wav'};
Daniel@0 18 % seq_wavwrite(files,'C:\combined.wav');
Daniel@0 19 %
Daniel@0 20 % You may want to copy only some parts of the files.
Daniel@0 21 % Therefore use the extra-option 'sequences':
Daniel@0 22 % seq_wavwrite(files,'C:\combined','sequences',segments);
Daniel@0 23 % ,where segments is an cell array the same size as the files_cellarray,
Daniel@0 24 % witch contains the position of the parts for every file.
Daniel@0 25 % Every cell row contains a struct array with the following fields:
Daniel@0 26 % abs_startspl and abs_stopspl
Daniel@0 27 % or
Daniel@0 28 % abs_startms and abs_stopms
Daniel@0 29 % You may also specify the channels that are to be copied in the field
Daniel@0 30 % channels
Daniel@0 31 % i.e.: files={'C:\wav\test1.wav','C:\other_wav\test2.wav'};
Daniel@0 32 % segsforfile1(1).abs_startspl=1;
Daniel@0 33 % segsforfile1(1).abs_stopspl=44100;
Daniel@0 34 % segsforfile1(2).abs_startspl=88200;
Daniel@0 35 % segsforfile1(2).abs_stopspl=200000;
Daniel@0 36 % segsforfile2(1).abs_startms=1;
Daniel@0 37 % segsforfile2(1).abs_stopms=2000;
Daniel@0 38 % segsforfile2(1).channels=[1 2]; <- use the first two channels
Daniel@0 39 % segments={segsforfile1,segsforfile2};
Daniel@0 40 % seq_wavwrite(files,'C:\combined','sequences',segments);
Daniel@0 41 %
Daniel@0 42 % If you want to copy specific files as a whole, just omit their abs_...
Daniel@0 43 % values.
Daniel@0 44 %
Daniel@0 45 % seq_wavwrite uses blockwise file processing to be able to copy large
Daniel@0 46 % amounts of data. The option 'max_chunksize' allows you to specify the
Daniel@0 47 % blocksize in samples. Keep in mind that in multichannel mode the actual
Daniel@0 48 % blocksize will be chunksize times channels.
Daniel@0 49 % i.e.: seq_wavwrite('C:\wav\','C:\combined.wav','max_chunksize',44100*60)
Daniel@0 50
Daniel@0 51 % Parse inputs:
Daniel@0 52
Daniel@0 53 [slash,leftargs]=process_options(varargin,'systemslash','\');
Daniel@0 54
Daniel@0 55 if ischar(in_files)
Daniel@0 56 data_names=dir(strcat(in_files,slash,'*.wav'));
Daniel@0 57 in_files=strcat(in_files,{data_names.name});
Daniel@0 58 end
Daniel@0 59
Daniel@0 60 [tmp_sig,tmp_Fs,tmp_nbits]=wavread(char(in_files{1}),[1 2]);
Daniel@0 61 tmp_channels=size(tmp_sig,2);
Daniel@0 62
Daniel@0 63 def_max_chunk_size = 44100*60*2;%chunksize nearly one minute at 44,1 khz sample rate
Daniel@0 64 [sequences,Fs,nbits,channels,max_chunk_size]=process_options(leftargs,'sequences',[],'Fs',...
Daniel@0 65 tmp_Fs,'nbits',tmp_nbits,'channels',tmp_channels,'max_chunksize',def_max_chunk_size);
Daniel@0 66
Daniel@0 67 if ischar(in_files) && ~isempty(sequences)
Daniel@0 68 warning('segment parameters ignored in directory-input mode')
Daniel@0 69 sequences=[];
Daniel@0 70 end
Daniel@0 71
Daniel@0 72 % Determine number of bytes in chunks
Daniel@0 73 % (not including pad bytes, if needed):
Daniel@0 74 % ----------------------------------
Daniel@0 75 % 'RIFF' 4 bytes
Daniel@0 76 % size 4 bytes
Daniel@0 77 % 'WAVE' 4 bytes
Daniel@0 78 % 'fmt ' 4 bytes
Daniel@0 79 % size 4 bytes
Daniel@0 80 % <wave-format> 14 bytes
Daniel@0 81 % <format_specific> 2 bytes (PCM)
Daniel@0 82 % 'data' 4 bytes
Daniel@0 83 % size 4 bytes
Daniel@0 84 % <wave-data> N bytes
Daniel@0 85 % ----------------------------------
Daniel@0 86
Daniel@0 87 bytes_per_sample = ceil(nbits/8);
Daniel@0 88 fmt_cksize = 16; % Don't include 'fmt ' or its size field
Daniel@0 89
Daniel@0 90 % Open file for output:
Daniel@0 91 [fid,err] = OpenWaveWrite(wavefile);
Daniel@0 92 error(err);
Daniel@0 93 try
Daniel@0 94 % Prepare basic chunk structure fields:
Daniel@0 95 ck=[]; ck.fid=fid; ck.filename = wavefile;
Daniel@0 96
Daniel@0 97 fwrite(fid,zeros(1,20),'uchar'); %skip previous chunks
Daniel@0 98 % Write <wave-format>:
Daniel@0 99 fmt.filename = wavefile;
Daniel@0 100 if nbits == 32,
Daniel@0 101 fmt.wFormatTag = 3; % Data encoding format (1=PCM, 3=Type 3 32-bit)
Daniel@0 102 else
Daniel@0 103 fmt.wFormatTag = 1;
Daniel@0 104 end
Daniel@0 105 fmt.nSamplesPerSec = Fs; % Samples per second
Daniel@0 106 fmt.nAvgBytesPerSec = channels*bytes_per_sample*Fs; % Avg transfer rate
Daniel@0 107 fmt.nBlockAlign = channels*bytes_per_sample; % Block alignment
Daniel@0 108 fmt.nBitsPerSample = nbits; % standard <PCM-format-specific> info
Daniel@0 109 fmt.nChannels = channels; % Number of channels
Daniel@0 110 error(write_wavefmt(fid,fmt));
Daniel@0 111
Daniel@0 112 fwrite(fid,zeros(1,8),'uchar'); %skip following chunks
Daniel@0 113
Daniel@0 114 % Write all audio data
Daniel@0 115 sample_sum=0;
Daniel@0 116 for filei=1:size(in_files,2)
Daniel@0 117 resamplewarn=0;
Daniel@0 118 channelwarn=0;
Daniel@0 119 if ~isempty(sequences)&& ~isempty(sequences{filei})
Daniel@0 120 numsegs=size(sequences{filei},2);
Daniel@0 121 else numsegs=1;
Daniel@0 122 end
Daniel@0 123 for seqi=1:numsegs;
Daniel@0 124 tmp_fsiz=wavread(char(in_files{filei}),'size');
Daniel@0 125 tmp_fsiz=tmp_fsiz(1);
Daniel@0 126 [y,tmp_fs,null]=wavread(char(in_files{filei}),[1 2]);%read data
Daniel@0 127 if ~isempty(sequences) && ~isempty(sequences{filei})
Daniel@0 128 if isfield(sequences{filei}(seqi),'abs_startspl')
Daniel@0 129 spl_seq=[sequences{filei}(seqi).abs_startspl sequences{filei}(seqi).abs_stopspl];
Daniel@0 130 elseif isfield(sequences{filei}(seqi),'abs_startms')
Daniel@0 131 spl_seq=floor([sequences{filei}(seqi).abs_startms sequences{filei}(seqi).abs_stopms].*tmp_fs./1000);
Daniel@0 132 else
Daniel@0 133 spl_seq=[1 tmp_fsiz];
Daniel@0 134 end
Daniel@0 135 if (spl_seq(1)< 1) || (spl_seq(2) > tmp_fsiz)
Daniel@0 136 warning('correcting segment range, not necessary critical in miliseconds-mode')
Daniel@0 137 spl_seq(1)=max(spl_seq(1),1);
Daniel@0 138 spl_seq(2)=min(spl_seq(2),tmp_fsiz);
Daniel@0 139 end
Daniel@0 140 else
Daniel@0 141 spl_seq=[1 tmp_fsiz];
Daniel@0 142 end
Daniel@0 143 win_start=spl_seq(1);
Daniel@0 144 win_stop=(min(spl_seq(2),spl_seq(1)+max_chunk_size-1));
Daniel@0 145 while win_stop <= spl_seq(2)
Daniel@0 146 [y,tmp_fs,null]=wavread(char(in_files{filei}),[win_start win_stop]);%read data
Daniel@0 147 if (size(y,2) > 1) && ~isempty(sequences) && isfield(sequences{filei}(seqi),'channels') %choose channel
Daniel@0 148 if size(y,2) >= max(sequences{filei}(seqi).channels)
Daniel@0 149 y=y(:,sequences{filei}(seqi).channels);
Daniel@0 150 else
Daniel@0 151 if ~channelwarn
Daniel@0 152 warning('ignoring errorneous channel field');
Daniel@0 153 channelwarn=1;
Daniel@0 154 end
Daniel@0 155 end
Daniel@0 156 end
Daniel@0 157 if (tmp_fs ~= Fs) %resample data if necessary
Daniel@0 158 if ~resamplewarn
Daniel@0 159 fprintf('seq_wavwrite.m: resampling from %d to %d Hz. \n',tmp_fs,Fs);
Daniel@0 160 resamplewarn=1;
Daniel@0 161 end
Daniel@0 162 y=resample(y,Fs,tmp_fs);
Daniel@0 163 end
Daniel@0 164 [samples,akt_channels] = size(y);
Daniel@0 165 if akt_channels > channels % if necessary make equivalent channelnum
Daniel@0 166 y=y(:,1:channels);
Daniel@0 167 elseif akt_channels < channels
Daniel@0 168 y=[y repmat(y(:,end),1,channels-akt_channels)];
Daniel@0 169 end
Daniel@0 170 error(write_wavedat(fid,fmt,y));
Daniel@0 171 sample_sum=sample_sum+samples;
Daniel@0 172
Daniel@0 173 if win_stop == spl_seq(2), break;
Daniel@0 174 end
Daniel@0 175 win_start=win_start+max_chunk_size;
Daniel@0 176 win_stop=(min(spl_seq(2),win_stop+max_chunk_size));
Daniel@0 177 end
Daniel@0 178 end
Daniel@0 179 end
Daniel@0 180 clear y;
Daniel@0 181
Daniel@0 182 total_samples = sample_sum * channels;
Daniel@0 183 total_bytes = total_samples * bytes_per_sample;
Daniel@0 184 data_cksize = total_bytes;
Daniel@0 185
Daniel@0 186 riff_cksize = 36+total_bytes;
Daniel@0 187
Daniel@0 188 % Determine pad bytes:
Daniel@0 189 % Determine if a pad-byte must be appended to data chunk:
Daniel@0 190 if rem(data_cksize, 2) ~= 0,
Daniel@0 191 fwrite(fid,0,'uchar');
Daniel@0 192 end
Daniel@0 193 data_pad = rem(data_cksize,2);
Daniel@0 194 riff_cksize = riff_cksize + data_pad; % + fmt_pad, always 0
Daniel@0 195
Daniel@0 196 % Write RIFF chunk:
Daniel@0 197 fseek(fid,0,'bof');
Daniel@0 198 ck.ID = 'RIFF';
Daniel@0 199 ck.Size = riff_cksize;
Daniel@0 200 error(write_ckinfo(ck));
Daniel@0 201
Daniel@0 202 % Write WAVE subchunk:
Daniel@0 203 ck.ID = 'WAVE';
Daniel@0 204 ck.Size = []; % Indicate a subchunk (no chunk size)
Daniel@0 205 error(write_ckinfo(ck));
Daniel@0 206
Daniel@0 207 % Write <fmt-ck>:
Daniel@0 208 ck.ID = 'fmt ';
Daniel@0 209 ck.Size = fmt_cksize;
Daniel@0 210 error(write_ckinfo(ck));
Daniel@0 211
Daniel@0 212 % Write <data-ck>:
Daniel@0 213 fseek(fid,36,'bof');
Daniel@0 214 ck.ID = 'data';
Daniel@0 215 ck.Size = data_cksize;
Daniel@0 216 error(write_ckinfo(ck));
Daniel@0 217 err='';
Daniel@0 218 catch
Daniel@0 219 err=lasterr;
Daniel@0 220 end
Daniel@0 221 % Close file:
Daniel@0 222 fclose(fid);
Daniel@0 223
Daniel@0 224 error(err);
Daniel@0 225 % end of wavwrite()
Daniel@0 226
Daniel@0 227
Daniel@0 228 % ------------------------------------------------------------------------
Daniel@0 229 % Private functions:
Daniel@0 230 % ------------------------------------------------------------------------
Daniel@0 231
Daniel@0 232
Daniel@0 233 % ------------------------------------------------------------------------
Daniel@0 234 function [fid,err] = OpenWaveWrite(wavefile)
Daniel@0 235 % OpenWaveWrite
Daniel@0 236 % Open WAV file for writing.
Daniel@0 237 % If filename does not contain an extension, add ".wav"
Daniel@0 238
Daniel@0 239 fid = [];
Daniel@0 240 err = '';
Daniel@0 241 if ~isstr(wavefile),
Daniel@0 242 err='Wave file name must be a string.'; return;
Daniel@0 243 end
Daniel@0 244 if isempty(findstr(wavefile,'.')),
Daniel@0 245 wavefile=[wavefile '.wav'];
Daniel@0 246 end
Daniel@0 247 % Open file, little-endian:
Daniel@0 248 [fid,err] = fopen(wavefile,'wb','l');
Daniel@0 249
Daniel@0 250 return
Daniel@0 251
Daniel@0 252
Daniel@0 253 % ------------------------------------------------------------------------
Daniel@0 254 function err = write_ckinfo(ck)
Daniel@0 255 % WRITE_CKINFO: Writes next RIFF chunk, but not the chunk data.
Daniel@0 256 % Assumes the following fields in ck:
Daniel@0 257 % .fid File ID to an open file
Daniel@0 258 % .ID 4-character string chunk identifier
Daniel@0 259 % .Size Size of chunk (empty if subchunk)
Daniel@0 260 %
Daniel@0 261 %
Daniel@0 262 % Expects an open FID pointing to first byte of chunk header,
Daniel@0 263 % and a chunk structure.
Daniel@0 264 % ck.fid, ck.ID, ck.Size, ck.Data
Daniel@0 265
Daniel@0 266 errmsg = ['Failed to write ' ck.ID ' chunk to WAVE file: ' ck.filename];
Daniel@0 267 err = '';
Daniel@0 268
Daniel@0 269 if (fwrite(ck.fid, ck.ID, 'char') ~= 4),
Daniel@0 270 err=errmsg; return;
Daniel@0 271 end
Daniel@0 272
Daniel@0 273 if ~isempty(ck.Size),
Daniel@0 274 % Write chunk size:
Daniel@0 275 if (fwrite(ck.fid, ck.Size, 'uint32') ~= 1),
Daniel@0 276 err=errmsg; return;
Daniel@0 277 end
Daniel@0 278 end
Daniel@0 279
Daniel@0 280 return
Daniel@0 281
Daniel@0 282 % ------------------------------------------------------------------------
Daniel@0 283 function err = write_wavefmt(fid, fmt)
Daniel@0 284 % WRITE_WAVEFMT: Write WAVE format chunk.
Daniel@0 285 % Assumes fid points to the wave-format subchunk.
Daniel@0 286 % Requires chunk structure to be passed, indicating
Daniel@0 287 % the length of the chunk.
Daniel@0 288
Daniel@0 289 errmsg = ['Failed to write WAVE format chunk to file' fmt.filename];
Daniel@0 290 err = '';
Daniel@0 291
Daniel@0 292 % Create <wave-format> data:
Daniel@0 293 if (fwrite(fid, fmt.wFormatTag, 'uint16') ~= 1) | ...
Daniel@0 294 (fwrite(fid, fmt.nChannels, 'uint16') ~= 1) | ...
Daniel@0 295 (fwrite(fid, fmt.nSamplesPerSec, 'uint32' ) ~= 1) | ...
Daniel@0 296 (fwrite(fid, fmt.nAvgBytesPerSec, 'uint32' ) ~= 1) | ...
Daniel@0 297 (fwrite(fid, fmt.nBlockAlign, 'uint16') ~= 1),
Daniel@0 298 err=errmsg; return;
Daniel@0 299 end
Daniel@0 300
Daniel@0 301 % Write format-specific info:
Daniel@0 302 if fmt.wFormatTag==1 | fmt.wFormatTag==3,
Daniel@0 303 % Write standard <PCM-format-specific> info:
Daniel@0 304 if (fwrite(fid, fmt.nBitsPerSample, 'uint16') ~= 1),
Daniel@0 305 err=errmsg; return;
Daniel@0 306 end
Daniel@0 307
Daniel@0 308 else
Daniel@0 309 err='Unknown data format.';
Daniel@0 310 end
Daniel@0 311
Daniel@0 312 return
Daniel@0 313
Daniel@0 314
Daniel@0 315 % -----------------------------------------------------------------------
Daniel@0 316 function y = PCM_Quantize(x, fmt)
Daniel@0 317 % PCM_Quantize:
Daniel@0 318 % Scale and quantize input data, from [-1, +1] range to
Daniel@0 319 % either an 8-, 16-, or 24-bit data range.
Daniel@0 320
Daniel@0 321 % Clip data to normalized range [-1,+1]:
Daniel@0 322 ClipMsg = ['Data clipped during write to file:' fmt.filename];
Daniel@0 323 ClipWarn = 0;
Daniel@0 324
Daniel@0 325 % Determine slope (m) and bias (b) for data scaling:
Daniel@0 326 nbits = fmt.nBitsPerSample;
Daniel@0 327 m = 2.^(nbits-1);
Daniel@0 328
Daniel@0 329 switch nbits
Daniel@0 330 case 8,
Daniel@0 331 b=128;
Daniel@0 332 case {16,24},
Daniel@0 333 b=0;
Daniel@0 334 otherwise,
Daniel@0 335 error('Invalid number of bits specified.');
Daniel@0 336 end
Daniel@0 337
Daniel@0 338 y = round(m .* x + b);
Daniel@0 339
Daniel@0 340 % Determine quantized data limits, based on the
Daniel@0 341 % presumed input data limits of [-1, +1]:
Daniel@0 342 ylim = [-1 +1];
Daniel@0 343 qlim = m * ylim + b;
Daniel@0 344 qlim(2) = qlim(2)-1;
Daniel@0 345
Daniel@0 346 % Clip data to quantizer limits:
Daniel@0 347 i = find(y < qlim(1));
Daniel@0 348 if ~isempty(i),
Daniel@0 349 warning(ClipMsg); ClipWarn=1;
Daniel@0 350 y(i) = qlim(1);
Daniel@0 351 end
Daniel@0 352
Daniel@0 353 i = find(y > qlim(2));
Daniel@0 354 if ~isempty(i),
Daniel@0 355 if ~ClipWarn, warning(ClipMsg); end
Daniel@0 356 y(i) = qlim(2);
Daniel@0 357 end
Daniel@0 358
Daniel@0 359 return
Daniel@0 360
Daniel@0 361
Daniel@0 362 % -----------------------------------------------------------------------
Daniel@0 363 function err = write_wavedat(fid,fmt,data)
Daniel@0 364 % WRITE_WAVEDAT: Write WAVE data chunk
Daniel@0 365 % Assumes fid points to the wave-data chunk
Daniel@0 366 % Requires <wave-format> structure to be passed.
Daniel@0 367
Daniel@0 368 err = '';
Daniel@0 369
Daniel@0 370 if fmt.wFormatTag==1 | fmt.wFormatTag==3,
Daniel@0 371 % PCM Format
Daniel@0 372
Daniel@0 373 % 32-bit Type 3 is normalized, so no scaling needed.
Daniel@0 374 if fmt.nBitsPerSample ~= 32,
Daniel@0 375 data = PCM_Quantize(data, fmt);
Daniel@0 376 end
Daniel@0 377
Daniel@0 378 switch fmt.nBitsPerSample
Daniel@0 379 case 8,
Daniel@0 380 dtype='uchar'; % unsigned 8-bit
Daniel@0 381 case 16,
Daniel@0 382 dtype='int16'; % signed 16-bit
Daniel@0 383 case 24,
Daniel@0 384 dtype='bit24'; % signed 24-bit
Daniel@0 385 case 32,
Daniel@0 386 dtype='float'; % normalized 32-bit floating point
Daniel@0 387 otherwise,
Daniel@0 388 err = 'Invalid number of bits specified.'; return;
Daniel@0 389 end
Daniel@0 390
Daniel@0 391 % Write data, one row at a time (one sample from each channel):
Daniel@0 392 [samples,channels] = size(data);
Daniel@0 393 total_samples = samples*channels;
Daniel@0 394
Daniel@0 395 if (fwrite(fid, reshape(data',total_samples,1), dtype) ~= total_samples),
Daniel@0 396 err = 'Failed to write PCM data samples.'; return;
Daniel@0 397 end
Daniel@0 398
Daniel@0 399
Daniel@0 400 else
Daniel@0 401 % Unknown wave-format for data.
Daniel@0 402 err = 'Unsupported data format.';
Daniel@0 403 end
Daniel@0 404
Daniel@0 405 return
Daniel@0 406
Daniel@0 407 % end of wavwrite.m