How to change audio speed without changing pitch?

5.9k views Asked by At

I need to apply audio to video at certain time with certain duration, but some audio duration is bigger(or smaller) then needed. How to change speed of audio without changing pitch? I tried to change fps(by multiplying to division of needed duration to audio duration) but it is not work as I want.

original = VideoFileClip("orig.mp4")
clips = [orig.audio.volumex(0.3)]
subs = [] #some array
i = 0
for sub in subs:
    clip = AudioFileClip("\\temp{}.mp3")
    mult = clip.duration / (sub.end - sub.start)  + 0.00001
    clip = AudioArrayClip(clip.to_soundarray(buffersize=500, fps=24000/mult), fps=24000).set_start(sub.start).set_end(sub.end)
    clips.append(clip)
    i += 1

final = CompositeAudioClip(clips)
final.write_audiofile("final.mp3")
2

There are 2 answers

1
SerialDev On

Using wave: Change the sampling rate

import wave

CHANNELS = 1
swidth = 2
Change_RATE = 2

spf = wave.open('VOZ.wav', 'rb')
RATE=spf.getframerate()
signal = spf.readframes(-1)

wf = wave.open('changed.wav', 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(swidth)
wf.setframerate(RATE*Change_RATE)
wf.writeframes(signal)
wf.close()
5
dzbanecznix On

you can use librosa module:

from scipy.io import wavfile
import librosa, numpy as np

song, fs = librosa.load("song.wav")

song_2_times_faster = librosa.effects.time_stretch(song, 2)

scipy.io.wavfile.write("song_2_times_faster.wav", fs, song_2_times_faster) # save the song