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@12
|
24 % TO DO: to save computation: take shortest file?
|
b@3
|
25 masterAudioChannels = audioread([foldername '/' list(1).name]); % read file
|
b@2
|
26 masterAudio = sum(masterAudioChannels, 2); % sum to mono
|
b@2
|
27
|
b@2
|
28 % for each other file:
|
b@8
|
29 for i = 2:length(list)
|
b@2
|
30 slaveAudioChannels = audioread([foldername '/' list(i).name]); % read file
|
b@2
|
31 slaveAudio = sum(slaveAudioChannels, 2); % sum to mono
|
b@2
|
32
|
b@3
|
33 % check sampling rate is the same (or: express in terms of seconds)
|
b@2
|
34 % ...
|
b@3
|
35
|
b@2
|
36 % crosscorrelation function
|
b@3
|
37 [xc, timeaxis] = xcorr(masterAudio, slaveAudio);
|
b@3
|
38 [value, lag] = max(abs(xc));
|
b@3
|
39 shiftvec(i) = timeaxis(lag);
|
b@2
|
40
|
b@3
|
41 % debugging plots
|
b@3
|
42 % figure;
|
b@3
|
43 % title(['Crosscorrelation file 1 vs ' num2str(i)]);
|
b@3
|
44 % subplot(2,1,1);
|
b@3
|
45 % plot(timeaxis, xc);
|
b@3
|
46 % xlabel('Samples');
|
b@3
|
47 % ylabel('Crosscorrelation');
|
b@3
|
48 % subplot(2,1,2);
|
b@3
|
49 % plot(timeaxis, abs(xc));
|
b@3
|
50 % xlabel('Samples');
|
b@3
|
51 % ylabel('Absolute value of crosscorrelation');
|
b@2
|
52
|
b@2
|
53 % monitoring/debugging
|
b@2
|
54
|
b@2
|
55 end
|
b@3
|
56
|
b@3
|
57 % add absolute of largest negative lag worth of zeros to all;
|
b@3
|
58 % then add 'shiftvec' value to that
|
b@3
|
59 maxlag = min(shiftvec);
|
b@3
|
60 for i = 1:length(list)
|
b@3
|
61 [audio, fs] = audioread([foldername '/' list(i).name]);
|
b@6
|
62 audiowrite([foldername '/' list(i).name], ...
|
b@3
|
63 [zeros(-maxlag + shiftvec(i), size(audio, 2)) ; audio], ...
|
b@3
|
64 fs, 'BitsPerSample', 24);
|
b@3
|
65 end
|
b@2
|
66
|
b@2
|
67 elapsedTime = toc; % stop measuring time
|
b@3
|
68 disp(['autoalign took ' num2str(elapsedTime) ...
|
b@3
|
69 ' seconds to align the files in folder ' foldername]);
|
b@2
|
70
|
b@2
|
71 end |