r4j

stft

r4j
Jul 15th, 2015
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.54 KB | None | 0 0
  1. function y = stft(x, N, win, hop, sr, pre_zeropadding)
  2. % y = stft(x, N, win, hop, sr)
  3. %   Short-time Fourier transform
  4. %   x: input vector (1-D)
  5. %   N: FFT size (default: 256)
  6. %   win: window size (when it is a scholar value) or window function (when
  7. %   it is given as a vector) (default: FFT size and Hann window)
  8. %   hop: hop size (default: half window size)
  9. %   sr: sampling rate (default: 8000Hz)
  10. %   pre_zeropadding: size of zeros attached to the beginning of x
  11. %
  12. % Juhan Nam
  13. % Feb-01-2013: initial version
  14.  
  15. if nargin < 2
  16.     N = 256;
  17. end
  18. if nargin < 3
  19.     win = N;
  20. end
  21. if nargin < 4
  22.     if length(win) > 1
  23.         hop = floor(length(win)/2);
  24.     else
  25.         hop = floor(win/2);        
  26.     end
  27. end
  28. if nargin < 5
  29.     sr = 8000;
  30. end
  31. if nargin < 6
  32.     pre_zeropadding = 0;
  33. end
  34.  
  35. % make x a column
  36. x = x(:);
  37.  
  38. if length(win) == 1
  39.     w = hann(win,'periodic');
  40. else
  41.     w = win;
  42. end
  43. w = w(:);
  44.  
  45. if length(w) > N
  46.     N = length(w);
  47. end
  48.  
  49. % if necessary, do pre-zeropadding for time alignment
  50. if pre_zeropadding > 0
  51.     x = [zeros(pre_zeropadding,1); x];
  52. end
  53.  
  54. % fit x to FFT size
  55. l = length(x);
  56. if l >= N
  57.     l2 = ceil((l-N)/hop)*hop + N;
  58. else
  59.     l2 = N;
  60. end
  61. x = [x; zeros(l2-l,1)];
  62. M = (l2-N)/hop+1;
  63.  
  64. % fft loop
  65. y = zeros(N/2+1, M);
  66. for k=1:M
  67.     temp = fft(w.*x((k-1)*hop+[1:length(w)]),N);
  68.     y(:,k) = temp(1:N/2+1);
  69. end
  70.  
  71. if nargout == 0
  72.     t = [0:M-1]*hop/sr;
  73.     f = [0:N/2]/N*sr;
  74.     imagesc(t,f,20*log10(abs(y)));
  75.     axis xy;
  76.     xlabel('time [sec]');
  77.     ylabel('freq. [Hz]');
  78. end
Advertisement
Add Comment
Please, Sign In to add comment