如何使用Pydub更改音频播放速度?

2024-10-16 20:51:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个新的学习者音频编辑libs-Pydub。我想用Pydub(比如.wav/mp3格式的文件)来改变一些音频文件的播放速度,但是我不知道怎么做。我看到的唯一可以处理这个问题的模块是speedup module in effect.py。但是,我不知道该怎么称呼它。在

有人能解释一下如何在Pydub完成这个任务吗?非常感谢!在

(一个相关的问题:Pydub - How to change frame rate without changing playback speed,但是我想做的是在不改变音质的情况下改变播放速度。)


Tags: 模块文件in格式学习者mp3速度音频文件
2条回答

在声音。设置帧速率()进行转换,它不应该引起任何“花栗鼠效应”,但你可以做的是改变帧速率(没有转换),然后将音频从那里转换回正常的帧速率(如44.1 kHz,“CD质量”)

from pydub import AudioSegment
sound = AudioSegment.from_file(…)

def speed_change(sound, speed=1.0):
    # Manually override the frame_rate. This tells the computer how many
    # samples to play per second
    sound_with_altered_frame_rate = sound._spawn(sound.raw_data, overrides={
         "frame_rate": int(sound.frame_rate * speed)
      })
     # convert the sound with altered frame rate to a standard frame rate
     # so that regular playback programs will work right. They often only
     # know how to play audio at standard frame rate (like 44.1k)
    return sound_with_altered_frame_rate.set_frame_rate(sound.frame_rate)


slow_sound = speed_change(sound, 0.75)
fast_sound = speed_change(sound, 2.0)

这可以通过使用pyrubberband软件包来实现,它需要橡胶带库,可以在保持音高和高质量的同时拉伸音频。我可以用brew在MacOS上安装这个库,在Ubuntu上也可以用apt安装。对于极限拉伸,请看PaulStretch

brew install rubberband

这只适用于librosa包

^{pr2}$

为了让pyrubberband直接与pydub的AudioSegment一起工作而不需要librosa,我修改了这个函数:

def change_audioseg_tempo(audiosegment, tempo, new_tempo):
    y = np.array(audiosegment.get_array_of_samples())
    if audiosegment.channels == 2:
        y = y.reshape((-1, 2))

    sample_rate = audiosegment.frame_rate

    tempo_ratio = new_tempo / tempo
    print(tempo_ratio)
    y_fast = pyrb.time_stretch(y, sample_rate, tempo_ratio)

    channels = 2 if (y_fast.ndim == 2 and y_fast.shape[1] == 2) else 1
    y = np.int16(y_fast * 2 ** 15)

    new_seg = pydub.AudioSegment(y.tobytes(), frame_rate=sample_rate, sample_width=2, channels=channels)

    return new_seg

相关问题 更多 >