title: How do I create a low pass filter for audio using fft
body: <p>I have tried to create a low pass filter for aiff files, but the sound coming out is white noise. I only understand the broad overview of how an FFT works, so I'm guessing my problems are related to that. </p>
  
  <p>Basically I open the audio file (of say a piano loop), convert it to mono, then perform an FFT on the samples, then I tried to remove the upper frequencies by setting them to zero. And finally I perform an IFTT and save the results to a new file.</p>
  
  <pre><code>import aifc
  import struct
  import numpy as np
  
  def getMonoSamples(fileName):
      enter code here`obj = aifc.open(fileName,'r')
      obj.setpos(0)
      numFrames = obj.getnframes()
      myFrames = obj.readframes(numFrames)
      samplingRate = obj.getframerate()
      data = struct.unpack('{n}h'.format(n=numFrames*2), myFrames)
      data = np.array(data)
      dataLeft =[]
      for i,x in enumerate(data):
          if i%2==1:
              dataLeft.append(x)
      obj.close()
      return dataLeft,numFrames,samplingRate
  
  def writeMonoFile(fileName,samples,nframes):
      mono_file=aifc.open(file, 'w')
      comptype="NONE"
      compname="not compressed"
      nchannels=1
      sampwidth=2
      mono_file.setparams((nchannels, sampwidth, int(sampling_rate), nframes, comptype, compname))
      print "writing sample aif..."
      for s in samples:
         mono_file.writeframes(struct.pack('h', s))
      mono_file.close()
  
  def lpFilter(dataFft):
      new =[None]*len(dataFft)
      for i,x in enumerate(dataFft):
          #if the frequency is above 5000, remove it
          if i&gt;5000:
              new[i]=0
          else:
              new[i]=x
      return new
  # get audio samples from a function that converts stereo to mono
  sampleData,numFrames,samplingRate = getMonoSamples('beetP2.aif') 
  dataFft = np.fft.fft(sampleData)
  filtered = lpFilter(dataFft)
  invFft = np.fft.ifft(filtered)
  invFft = [int(x) for x in invFft]
  file = "test.aif"
  writeMonoFile(file,invFft,numFrames)
  </code></pre>
  
  <p>I do get a warning: "ComplexWarning: Casting complex values to real discards the imaginary part" but I also get this warning when simply performing a stereo to mono conversion and saving. The audio seems to sound fine until I try to filter it. I'm guessing this is related, but not sure how to get around it.</p>
  
  <p>Any audio sample I filter winds up sounding like white noise instead of a filtered version of itself.</p>