b@3: function autoalign(foldername) b@3: % AUTOALIGN aligns audio in folder with selected file by inserting zeros b@3: % at the start of the files. b@2: % b@2: % by Brecht De Man at Centre for Digital Music on 17 November 2014 b@2: b@3: % error('Work in progress, function not finished'); % while unfinished b@2: b@2: tic; % start measuring time b@3: list = dir([foldername '/*.wav']); % get names of files b@2: b@2: % remove hidden files from list b@2: % see http://www.mathworks.co.uk/matlabcentral/newsreader/view_thread/258220 b@2: for k = length(list):-1:1 b@2: fname = list(k).name; b@2: if fname(1) == '.' b@2: list(k) = [ ]; b@2: end b@2: end b@3: b@3: shiftvec = zeros(length(list), 1); b@3: b@3: % first file: b@12: % TO DO: to save computation: take shortest file? b@3: masterAudioChannels = audioread([foldername '/' list(1).name]); % read file b@2: masterAudio = sum(masterAudioChannels, 2); % sum to mono b@2: b@2: % for each other file: b@8: for i = 2:length(list) b@2: slaveAudioChannels = audioread([foldername '/' list(i).name]); % read file b@2: slaveAudio = sum(slaveAudioChannels, 2); % sum to mono b@2: b@3: % check sampling rate is the same (or: express in terms of seconds) b@2: % ... b@3: b@2: % crosscorrelation function b@3: [xc, timeaxis] = xcorr(masterAudio, slaveAudio); b@3: [value, lag] = max(abs(xc)); b@3: shiftvec(i) = timeaxis(lag); b@2: b@3: % debugging plots b@3: % figure; b@3: % title(['Crosscorrelation file 1 vs ' num2str(i)]); b@3: % subplot(2,1,1); b@3: % plot(timeaxis, xc); b@3: % xlabel('Samples'); b@3: % ylabel('Crosscorrelation'); b@3: % subplot(2,1,2); b@3: % plot(timeaxis, abs(xc)); b@3: % xlabel('Samples'); b@3: % ylabel('Absolute value of crosscorrelation'); b@2: b@2: % monitoring/debugging b@2: b@2: end b@3: b@3: % add absolute of largest negative lag worth of zeros to all; b@3: % then add 'shiftvec' value to that b@3: maxlag = min(shiftvec); b@3: for i = 1:length(list) b@3: [audio, fs] = audioread([foldername '/' list(i).name]); b@6: audiowrite([foldername '/' list(i).name], ... b@3: [zeros(-maxlag + shiftvec(i), size(audio, 2)) ; audio], ... b@3: fs, 'BitsPerSample', 24); b@3: end b@2: b@2: elapsedTime = toc; % stop measuring time b@3: disp(['autoalign took ' num2str(elapsedTime) ... b@3: ' seconds to align the files in folder ' foldername]); b@2: b@2: end