title: Parameters to control the size of a spectrogram
body: <p>I am trying to get the spectrogram as described by the following instruction. </p>
  
  <blockquote>
    <p>Each audio segment has duration of 5s. Frames with equal size are
    extracted from the audio (with overlap between the consecutive frames), and each of the frame consists of 1024
    samples. The mel-scale is divided into 128 bins. Therefore, the
    spectrogram for the audio segment has the dimension of 192×128.</p>
  </blockquote>
  
  <p>To my knowledge, this instruction implies <code>n_mels=128</code> and <code>n_fft=1024</code> in the <code>melspectrogram</code>  function. So I tried to get a spectrogram with the following code:</p>
  
  <pre><code>from librosa import load, power_to_db
  from librosa.display import specshow
  from librosa.feature import melspectrogram
  
  audio_path = r'5s.wav'
  y, sr = load(audio_path,sr=44100)
  S = melspectrogram(y,sr,n_mels=128,n_fft=1024,hop_length=512)
  print(S.shape)
  </code></pre>
  
  <p>The shape of <code>y</code> is <code>(220500,)</code> and the sampling rate <code>sr</code> is <code>44100</code> And the spectrogram shape I get is <code>(128, 431)</code>. The <code>128 mel-scale</code> size is correct, yet the number of frames I get is <code>431</code> instead of <code>192</code> frames mentioned in the instruction. </p>
  
  <p>In order to get 192 frames, I changed the sampling rate to <code>22050</code> and keep adjusting the <code>hop_lenght</code>until the spectrogram has <code>192</code> frames:</p>
  
  <pre><code>audio_path = r'5s.wav'
  y, sr = load(audio_path,sr=22050)
  S = melspectrogram(y,sr,n_mels=128,n_fft=1024,hop_length=575)
  print(S.shape)
  </code></pre>
  
  <p>However, I am not sure if it is the correct way to get the spectrogram dimension that I want. It seems the process is just trial and error. I wonder if there is a more scientific way to get a spectrogram with the shape that I want without guessing the parameter values?</p>