您可能需要考虑一些用于处理音频的包:soundfile 通常用于 I/O,librosa 也是如此。 “采样率”又名“帧率”是每秒的音频样本数,通常以 kHz 为单位,但在软件中仅以 Hz 为单位。
还有一个专门的Sound Design StackExchange,您可能会发现搜索更有成效。
获取文件的一部分称为“寻找”,soundfile.SoundFile 类支持它。
这个想法是将“光标”的位置移动到特定的帧SoundFile.seek(pos),然后读入一些帧SoundFile.read(n_frames),之后光标的位置将移动那么多帧,您可以通过SoundFile.tell() 获取。
以下是访问 wav 文件的一部分的示例:
import soundfile as sf
def read_audio_section(filename, start_time, stop_time):
track = sf.SoundFile(filename)
can_seek = track.seekable() # True
if not can_seek:
raise ValueError("Not compatible with seeking")
sr = track.samplerate
start_frame = sr * start_time
frames_to_read = sr * (stop_time - start_time)
track.seek(start_frame)
audio_section = track.read(frames_to_read)
return audio_section, sr
...要将其写入文件,您只需使用soundfile.write(注意:包中的一个函数,而不是soundfile.SoundFile 类的方法)
def extract_as_clip(input_filename, output_filename, start_time, stop_time):
audio_extract, sr = read_audio_section(input_filename, start_time, stop_time)
sf.write(output_filename, audio_extract, sr)
return