Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trimming audio in python

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?

like image 488
Nick yo Avatar asked Oct 15 '13 05:10

Nick yo


People also ask

How do you trim audio in Python?

We can do this using the pip command as shown below in your terminal or shell. After executing the above command pydub will be installed in your machine. In the next code, we can select the duration of the file we want to cut. Or we can select the portion we required.


1 Answers

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)
like image 97
Paul Avatar answered Jan 03 '23 13:01

Paul