import numpy as np
import wave
# Start opening the file with wave
with wave.open('filename.wav') as f:
# Read the whole file into a buffer. If you are dealing with a large file
# then you should read it in blocks and process them separately.
buffer = f.readframes(f.getnframes())
# Convert the buffer to a numpy array by checking the size of the sample
# width in bytes. The output will be a 1D array with interleaved channels.
interleaved = np.frombuffer(buffer, dtype=f'int{f.getsampwidth()*8}')
# Reshape it into a 2D array separating the channels in columns.
data = np.reshape(interleaved, (-1, f.getnchannels()))
# play_wav.py
import sounddevice as sd
import numpy as np
import wave
from typing import Tuple
from pathlib import Path
# Utility function that reads the whole `wav` file content into a numpy array
def wave_read(filename: Path) -> Tuple[np.ndarray, int]:
with wave.open(str(filename), 'rb') as f:
buffer = f.readframes(f.getnframes())
inter = np.frombuffer(buffer, dtype=f'int{f.getsampwidth()*8}')
return np.reshape(inter, (-1, f.getnchannels())), f.getframerate()
if __name__ == '__main__':
# Play all files in the current directory
for wav_file in Path().glob('*.wav'):
print(f"Playing {wav_file}")
data, fs = wave_read(wav_file)
sd.play(data, samplerate=fs, blocking=True)
2条答案
按热度按时间8ehkhllq1#
为了与@Marco的评论保持一致,您可以查看Scipy库,特别是
scipy.io
。要读取您的文件('filename.wav'),只需执行
这将输出一个元组(我将其命名为“输出”):
output[0]
,采样率output[1]
,要分析的示例数组7uzetpgm2#
这可以通过几行
wave
(内置)和numpy
(显然)来实现。您不需要使用librosa
、scipy
或soundfile
。最新的给我的问题阅读wav
文件,这是整个原因,我写在这里现在。我喜欢将它打包到一个函数中,该函数返回采样频率并与
pathlib.Path
对象一起工作。这样就可以使用sounddevice
播放