【PYTHON】soundfile.read / torchaudio.load / librosa.load

本文介绍了三种Python音频读取方法:soundfile.read、torchaudio.load和librosa.load,分别解析它们的参数、返回类型和特点。soundfile.read是最简单的,Torchaudio.load返回Tensor,Librosa.load允许设置声道和采样率。对比了三者的输出差异。

目录

Soundfile.read

Torchaudio.load

Librosa.load


在读取音频时有几种方法,而每一种所读出来的格式都不一样

Soundfile.read

最简单输入参数也最少的方式

import soundfile as sf

file = './my_audio/cat.wav'
y, sr = sf.read(file)
print('If use soundfile, shape of y = ',y.shape)

# 输出:
If use soundfile.read, shape of y =  (187662, 2)

Torchaudio.load

读取完音频则为Tensor的型态

filepath (str):音频路径。

frame_offset (int)(默认是0):在此之后开始读取,以帧为单位。

num_frames (int)(默认是-1):读取的最大帧数。默认是表示从frame_offset直到末尾。若给定文件帧数不足,可能返回实际剩余的帧数。

normalize (bool)(默认为 True):True时,函数返回float32,所有值归一化到[-1,1]之间。
若输入文件是wav,且是整形,且为False时,则输出int。此参数仅对wav文件起作用。

channels_first (bool)(默认为 True):True时,返回的Tensor是[channel, time];False时,返回的Tensor是[time, channel]。

import torchaudio

file = './my_audio/cat.wav'
y, sr = torchaudio.load(file)
print('If use torchaudio.load, shape of y = ',y.shape)

# 输出:
If use torchaudio.load, shape of y =  torch.Size([2, 187662])

Librosa.load

采用liborsa可直接设定是以单声道或是双声道读取,也能直接设置采样率

path (str):音频路径。

sr (int)(默认22050):采样率,sr=None表读取原始采样率。

mono (bool):True为单声道;False为双声道

offset (str):在此时间之后开始读取(单位:秒)。

duration (str):仅读取这些时长的音频的(单位:秒)。

import librosa

file = './my_audio/cat.wav'
y, sr = librosa.load(file, sr=44100, mono=False)
print('If use librosa.load, shape of y = ',y.shape)

# 输出:
If use librosa.load, shape of y =  (2, 187662)

三者输出比較:

# 三者输出比較:
If use soundfile.read, shape of y =  (187662, 2)
If use torchaudio.load, shape of y =  torch.Size([2, 187662])
If use librosa.load, shape of y =  (2, 187662)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值