annotate aux/autoalign.m @ 3:1f7b986dab05

Added autoalign.m: aligns audio by zero-padding before the signal to align the peak of the crosscorrelation function
author Brecht De Man <b.deman@qmul.ac.uk>
date Mon, 17 Nov 2014 23:01:09 +0000
parents 5e72201496c8
children ed0a8621b96a
rev   line source
b@3 1 function autoalign(foldername)
b@3 2 % AUTOALIGN aligns audio in folder with selected file by inserting zeros
b@3 3 % at the start of the files.
b@2 4 %
b@2 5 % by Brecht De Man at Centre for Digital Music on 17 November 2014
b@2 6
b@3 7 % error('Work in progress, function not finished'); % while unfinished
b@2 8
b@2 9 tic; % start measuring time
b@3 10 list = dir([foldername '/*.wav']); % get names of files
b@2 11
b@2 12 % remove hidden files from list
b@2 13 % see http://www.mathworks.co.uk/matlabcentral/newsreader/view_thread/258220
b@2 14 for k = length(list):-1:1
b@2 15 fname = list(k).name;
b@2 16 if fname(1) == '.'
b@2 17 list(k) = [ ];
b@2 18 end
b@2 19 end
b@3 20
b@3 21 shiftvec = zeros(length(list), 1);
b@3 22
b@3 23 % first file:
b@3 24 masterAudioChannels = audioread([foldername '/' list(1).name]); % read file
b@2 25 masterAudio = sum(masterAudioChannels, 2); % sum to mono
b@2 26
b@2 27 % for each other file:
b@2 28 for i = 1:length(list)
b@2 29 slaveAudioChannels = audioread([foldername '/' list(i).name]); % read file
b@2 30 slaveAudio = sum(slaveAudioChannels, 2); % sum to mono
b@2 31
b@3 32 % check sampling rate is the same (or: express in terms of seconds)
b@2 33 % ...
b@3 34
b@2 35 % crosscorrelation function
b@3 36 [xc, timeaxis] = xcorr(masterAudio, slaveAudio);
b@3 37 [value, lag] = max(abs(xc));
b@3 38 shiftvec(i) = timeaxis(lag);
b@2 39
b@3 40 % debugging plots
b@3 41 % figure;
b@3 42 % title(['Crosscorrelation file 1 vs ' num2str(i)]);
b@3 43 % subplot(2,1,1);
b@3 44 % plot(timeaxis, xc);
b@3 45 % xlabel('Samples');
b@3 46 % ylabel('Crosscorrelation');
b@3 47 % subplot(2,1,2);
b@3 48 % plot(timeaxis, abs(xc));
b@3 49 % xlabel('Samples');
b@3 50 % ylabel('Absolute value of crosscorrelation');
b@2 51
b@2 52 % monitoring/debugging
b@2 53
b@2 54 end
b@3 55
b@3 56 % add absolute of largest negative lag worth of zeros to all;
b@3 57 % then add 'shiftvec' value to that
b@3 58 maxlag = min(shiftvec);
b@3 59 for i = 1:length(list)
b@3 60 [audio, fs] = audioread([foldername '/' list(i).name]);
b@3 61 audiowrite([foldername '/SHIFT' list(i).name], ... % remove SHIFT
b@3 62 [zeros(-maxlag + shiftvec(i), size(audio, 2)) ; audio], ...
b@3 63 fs, 'BitsPerSample', 24);
b@3 64 end
b@2 65
b@2 66 elapsedTime = toc; % stop measuring time
b@3 67 disp(['autoalign took ' num2str(elapsedTime) ...
b@3 68 ' seconds to align the files in folder ' foldername]);
b@2 69
b@2 70 end