Trimming audio in python

13,737

Let's assume that you read in the wave file using scipy.

Then you need to have "edit points" These are in and out values (in seconds for example) that the user would like to keep. you could get these from a file or from displaying the wave file and getting clicks from the mouse. If the user gives parts of the audio file that should be removed then this would need to be first negated

This is not the most efficient solution but should be ok for many scenarios.

import scipy.io.wavfile
fs1, y1 = scipy.io.wavfile.read(filename)
l1 = numpy.array([  [7.2,19.8], [35.3,67.23], [103,110 ] ])
l1 = ceil(l1*fs1)#get integer indices into the wav file - careful of end of array reading with a check for greater than y1.shape
newWavFileAsList = []
for elem in l1:
  startRead = elem[0]
  endRead = elem[1]
  if startRead >= y1.shape[0]:
    startRead = y1.shape[0]-1
  if endRead >= y1.shape[0]:
    endRead = y1.shape[0]-1
  newWavFileAsList.extend(y1[startRead:endRead])


newWavFile = numpy.array(newWavFileAsList)

scipy.io.wavfile.write(outputName, fs1, newWavFile)
Share:
13,737
Nick yo
Author by

Nick yo

Updated on June 05, 2022

Comments

  • Nick yo
    Nick yo about 2 years

    ok so im using pyaudio as well but from what I been looking at the wave module could maybe help me out here.

    So im trying to add a trimming function on my program, what I mean is im trying to allow the user to find parts of a wav. that he/she doesn't like and has the ability to trim the wave file to however he/she wants it.

    so far i been using pyaudio for just simple playback and pyaudio is really easy when it comes to recording from an input device.

    I been searching on pyaudio on anything I can do to trim audio but i really havent found anything that can help me. Though on the embedded wave module I see there are ways to set position.

    Would I have to have a loop or if statement done so that the program would know which positions to record and then have either pyaudio or the wave module to record the song from user set positions (beginning, end)? Would my program run efficiently if I approached it this way?

  • Nick yo
    Nick yo over 10 years
    are you also using the numpy module as well?
  • Nick yo
    Nick yo over 10 years
    and what would be the most efficient way to approach this?
  • Nick yo
    Nick yo over 10 years
    do you think I could se pyaudio with this?
  • Paul
    Paul over 10 years
    Yeah, I am using numpy and scipy. Numpy arrays and scipy to read/write the wav file. I think the code as given should be a good starting point for you. Then see where your bottlenecks are for ways to speed up. If you want to use pyaudio this Q&A can get you from pyaudio to numpy: stackoverflow.com/questions/9082431/…, but I think numpy/scipy should be fine for you reading wav files