Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

splitting wav file in python

Tags:

python

wav

I'm trying to split a wav file programmatically in Python. Based on hints from stackoverflow as well as the documentation from the Python wave module I'm doing the following

import wave

origAudio = wave.open('inputFile.wav','r')
frameRate = origAudio.getframerate()
nChannels = origAudio.getnchannels()
sampWidth = origAudio.getsampwidth()

start = float(someStartVal)
end = float(someEndVal)

origAudio.setpos(start*frameRate)
chunkData = origAudio.readframes(int((end-start)*frameRate))

chunkAudio = wave.open('outputFile.wav','w')
chunkAudio.setnchannels(nChannels)
chunkAudio.setsampwidth(sampWidth)
chunkAudio.setframerate(frameRate)
chunkAudio.writeframes(chunkData)
chunkAudio.close()

I iterate through a number of different start and end values, and extract chunks of audio from the original file in this manner. What's weird is that the technique works perfectly fine for some chunks, and produces garbage white noise for others. Also there's no obvious pattern of which start and end positions produce white noise, just that it happens consistently for an input file.

Anyone experienced this sort of behaviour before? Or know what I'm doing wrong? Suggestions on better ways of splitting an audio file programmatically are welcome.

Thanks in advance.

like image 308
user13321 Avatar asked Mar 22 '13 22:03

user13321


People also ask

How do I split a WAV file into multiple files in Python?

You can modify the snippet to suit your requirement. from pydub import AudioSegment t1 = t1 * 1000 #Works in milliseconds t2 = t2 * 1000 newAudio = AudioSegment. from_wav("oldSong. wav") newAudio = newAudio[t1:t2] newAudio.

Can you split a WAV file?

WavePad Audio File Splitter supports both lossy and lossless audio formats such as MP3, OGG, FLAC, and WAV. This software is available for Windows, macOS, iOS, and Android devices. It's free for home use with no time limits. What makes this program so versatile is the number of ways it can split audio files.

How do you trim audio in Python?

For working with Audio files here we are using 'pydub' library. By using this library we can play, cut, merge, split, or edit Audio files. For this first, we have to install 'pydub' library to our system. We can do this using the pip command as shown below in your terminal or shell.


1 Answers

This may have to do with start*frameRate being a float when calling setpos. Perhaps after readframes you should use tell to find the current location of the file pointer instead..

like image 57
unutbu Avatar answered Sep 25 '22 11:09

unutbu