PySoundFile 入门
PySoundFile是一个Python模块,用于读取和写入音频文件,将音频文件视为NumPy数组,包括音高和所有内容。该模块可以读取音频文件,即它从音频(.wav 文件)中提取 NumPy 数组并能够写入它
安装:运行以下 pip 命令:
pip install PySoundFile
PySoundFile 支持 libsndfile 支持的所有格式,例如 WAV、FLAC、OGG 和 MAT 文件
这是示例链接中使用的音频文件的链接
读取音频文件:
可以使用read()函数读取音频文件。
Syntax: read(file, frames=-1, start=0, stop=None, fill_value=None, samplerate=None, channels=None, subtype=None)
Parameters:
- file: path of the audio file
- frames: This argument is used to specify number of frames to read, by default it has -1 value indicating whole file to read
- start, stop: To specify start and end to read audio file, By default whole file is read
- fill_value: If there is less data left in the file than requested, the rest of the frames are filled with fill_value. If no fill_value is specified, the smaller array is returned
Returns: 2 values
- data: numpy array ( length should be 44,100 elements) If returned is 1-D numpy array then audio read is mono channeled
- samplerate: sample rate (or “sampling rate”) defines how many times per second a sound is sampled. Technically , it is the frequency of samples used in a digital recording. The standard sample rate used for audio CDs is 44.1 kilohertz for this file it is same too
支持的 文件格式:WAV、AIFF、AU、PAF、SVX、NIST、VOC、IRCAM、W64、MAT4、MAT5、PVF、XI、HTK、SDS、AVR、WAVEX、SD2、FLAC、CAF、WVE、OGG、MPC2K、RF64
示例:我们将读取以下文件:
Python3
# import the module
import soundfile as sf
# read the file
data, samplerate = sf.read('noice.wav')
# display the data
print(data)
print("---------------------")
print("Sample Rate is ", samplerate)
print("---------------------")
print("Done")
Python3
# imporintg the module
import soundfile as sf
# reading the file
data, samplerate = sf.read('Sample.wav')
# writing the file
sf.write('writing_file_output.wav', data, samplerate)
# You may compare both audio, link is given in the output
输出:
写入文件:我们可以使用write()函数写入文件。
Syntax: write(file, data, samplerate, subtype=None, endian=None, format=None, closefd=True)
Parameters:
- file: path of the output file
- data: data to be written
- samplerate: sample rate of the audio data
Returns: Nothing
要写入音频文件,我们需要 NumPy 数组(即数据),因为采样率具有标准值,它以 wb 模式打开文件,即如果存在相同的名称,则程序将重写它
示例:我们将读取以下文件:
蟒蛇3
# imporintg the module
import soundfile as sf
# reading the file
data, samplerate = sf.read('Sample.wav')
# writing the file
sf.write('writing_file_output.wav', data, samplerate)
# You may compare both audio, link is given in the output
输出:这是输出文件: