python读本地音频文件(转换成数组)的方式有很多,wave、scipy、librosa、torchaudio等。可有时候音频不在本地,而是从互联网传过来的,当然可以先保存到本地再读,但这样会多了硬盘读写的过程,数据下载下来本就经过内存,能不能直接取出来呢?
去度娘找了一遍没找到答案,便自己摸索了一下,被瞎猫撞到了死耗子,好像可以,用的是torchaudio.load()
,先上代码。
import torchaudio
import requests
from io import BytesIO
url = "https://downsc.chinaz.net/Files/DownLoad/sound1/202111/14994.wav" # 音频的URL
req = requests.get(url) # 下载音频
bt = BytesIO(req.content) # req.content是bytes类型的数据,得通过BytesIO包装一下才能得到torchaudio.load需要的参数类型
audio = torchaudio.load(bt)
audio
是这样的:
(tensor([[ 0.0000, 0.0000, 0.0000, ..., -0.0002, -0.0002, -0.0002],
[ 0.0000, 0.0000, 0.0000, ..., -0.0002, -0.0002, -0.0002]]), 44100)
这就是我要的效果啦。
版本说明
torch==1.8.0
torchaudio==0.8.0
试过torchaudio0.7.2,不可以。
能用就行,以下内容可忽略
torchaudio.load()
读音频需要传入一个filepath
参数,文档里对filepath
是这么解释的:
filepath (path-like object or file-like object):
Source of audio data. When the function is not compiled by TorchScript,
(e.g. ``torch.jit.script``), the following types are accepted;
* ``path-like``: file path
* ``file-like``: Object with ``read(size: int) -> bytes`` method,
which returns byte string of at most ``size`` length.
When the function is compiled by TorchScript, only ``str`` type is allowed.
Note: This argument is intentionally annotated as ``str`` only due to
TorchScript compiler compatibility.
重点在于filepath
可以是path-like
或file-like
,path-like
就是文件路径了,读本地音频就传文件路径;file-like
是一个Object with read(size: int) -> bytes
,什么意思?就是说,传入的这个对象得有一个函数叫read()
,接受int
类型的参数,返回bytes
类型的数据,BytesIO
就是符合这个条件的人选,所以就work了。
可能其它库也可以在内存中读音频,但由于本人用的是torch框架,装了torchaudio,不想再装太多库,没试过其它的方式。