I have a bunch of audio files. I am trying to crop the first and last 10% of the files off, keeping only the middle 80%.
Essentially what I am doing:
- read file
- get duration of audio file in seconds
- use ffmpeg to crop the file from duration0.1 to duration0.9
I am using this code:
import wave
import contextlib
import subprocess
import glob
data = []
duration_L = []
for path in glob.glob('audio/*/*.wav'):
name = str(path).split('/')[-1].split('.')[0]
label = str(path).split('/')[-2]
with contextlib.closing(wave.open(path,'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
duration = frames / float(rate)
duration_L.append([duration, label])
save_path = f"audio_edited/{label}/{name}.wav"
if duration >= 3:
command = f"ffmpeg -y -i {name_} -ss {duration*0.1} -to {duration*0.9} -c copy {save_path}"
subprocess.call(command, shell=True)
print('original length: ', duration)
print("0.1 of duration: ", duration*0.1)
print("0.9 of duration: ", duration*0.9)
print(f"file should now be {(duration*0.9) - (duration*0.1)} long")
with contextlib.closing(wave.open(save_path,'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
newduration = frames / float(rate)
print('new length is: ',newduration)
print("\n")
It appears to work okay on smaller duration files, but it breaks on larger ones. For example, here is a sample of the print out from a bunch of files:
original length: 3.3436734693877552
0.1 of duration: 0.33436734693877557
0.9 of duration: 3.00930612244898
file should now be 2.6749387755102045 long
new length is: 2.647074829931973
original length: 4.365351473922902
0.1 of duration: 0.43653514739229027
0.9 of duration: 3.928816326530612
file should now be 3.492281179138322 long
new length is: 3.4829931972789114
original length: 8.080544217687075
0.1 of duration: 0.8080544217687076
0.9 of duration: 7.272489795918368
file should now be 6.4644353741496605 long
new length is: 6.315827664399093
original length: 12.167256235827665
0.1 of duration: 1.2167256235827666
0.9 of duration: 10.950530612244899
file should now be 9.733804988662133 long
new length is: 5.897868480725624
original length: 5.061950113378685
0.1 of duration: 0.5061950113378685
0.9 of duration: 4.555755102040816
file should now be 4.049560090702948 long
new length is: 4.08671201814059
original length: 3.3901133786848074
0.1 of duration: 0.33901133786848076
0.9 of duration: 3.051102040816327
file should now be 2.712090702947846 long
new length is: 2.693514739229025
original length: 9.195102040816327
0.1 of duration: 0.9195102040816328
0.9 of duration: 8.275591836734694
file should now be 7.356081632653062 long
new length is: 6.222947845804988
Notice that on files over ~7 seconds, the new length is not what the file length should be. Instead the file is cropped to be much shorter.
What is going on?