如何使用numpy数组创建pydub AudioSegment?

a8jjtwal  于 11个月前  发布在  iOS
关注(0)|答案(2)|浏览(84)

下面的代码是用python写的

from scipy.io.wavfile import read
rate, signal = read('./data/input.wav')
# get only one channel
signal = signal[:,0] 
# do a bunch of processing here

字符串
现在我想使用'signal'和'rate'创建一个pydub段

audio_segment = pydub.AudioSegment()


那么,我如何创建这个音频片段,在此之后,我如何将信号作为一个numpy数组返回?

mcvgt66p

mcvgt66p1#

我可以在我的机器上运行这段代码:

from scipy.io.wavfile import read
from pydub import AudioSegment

rate, signal = read("./test/data/test1.wav")
channel1 = signal[:,0]

audio_segment = pydub.AudioSegment(
    channel1.tobytes(), 
    frame_rate=rate,
    sample_width=channel1.dtype.itemsize, 
    channels=1
)

# test that it sounds right (requires ffplay, or pyaudio):
from pydub.playback import play
play(audio_segment)

字符串

goucqfw6

goucqfw62#

如果你更喜欢一个函数:

from pydub import AudioSegment

def split_music(
        audio_file: AudioSegment | str,
        from_second: int = 0,
        to_second: int = None,
        save_file_path: str = None,
        save_file_format: str = "wav") -> AudioSegment:
    """
    This code splits an audio file based on the provided seconds
    :param audio_file: either a string to load from file or already loaded file as AudioSegment
    :param from_second: the second when the split starts
    :param to_second: the second when the split ends
    :param save_file_path: if provided audio snippet will be saved at location
    :param save_file_format: in which format to save the file
    :return: the audio snippet as AudioSegment
    """
    
    
    t1 = from_second * 1000  # Works in milliseconds
    t2 = to_second * 1000

    # load audio from file
    if type(audio_file) == str:
        AudioSegment.from_file(audio_file)

    # split audio
    audio_file = audio_file[t1:t2]

    if save_file_path is not None and type(save_file_path) == str:
        audio_file.export(save_file_path, format=save_file_format)  # Exports to a wav file in the curren

    return audio_file

字符串

相关问题