我目前正在寻找流音频文件的地方。我想从给定的.wav文件中读取x秒钟的时间,执行分析任务,然后重复.....

这是一些代码,以获得我想要的想法:

`read_x_seconds = 30
 file_length_in_min = 15
 for x in range(file_length_in_min * (60 / read_x_seconds)):
    y, fs = librosa.core.load(FILENAME, offset=x * read_x_seconds,
    duration=read_x_seconds)
    do_analysis(y, fs)`

最佳答案

假设我们正在考虑读取大量本地WAV文件的情况:

import wave
import numpy as np

def read_wav_part_from_local(path: str, start_s: float, duration_s: float):
    with wave.open(path, mode='rb') as wavread:
        fs = wavread.getframerate()
        start = int(start_s * fs)
        duration = int(duration_s * fs)
        wavread.setpos(start)
        wav_bytes = wavread.readframes(duration)

        if wavread.getsampwidth() == 2:
            dtype = 'int16'
        elif wavread.getsampwidth() == 4:
            dtype = 'int32'
        else:
            raise NotImplemented('I give up!')

        wav_array = np.frombuffer(wav_bytes, dtype=dtype)
        return wav_array, fs

如何使用它:
audio_chunk, fs = read_wav_part_from_local('your.wav', offset_in_s, duration_in_s)

关于python - 如何使用流读取音频文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56341792/

10-11 04:33