torchaudio的I/O函数

  1. info、load、save

1.1 info

torchaudio.info (filepath: str , ...)
Fetch meta data of an audio file. Refer to torchaudio.backend for the detail.
返回音频文件的meta信息

这里的meta元信息包括采样率、帧数、通道数、量化位数、音频格式

info = torchaudio.info(r'E:\adins\data\2s\test\cover\test60099_1.flac')
print(info)
输出meat信息
AudioMetaData(sample_rate=16000, num_frames=32000, num_channels=1, bits_per_sample=16, encoding=FLAC)

1.2 load

torchaudio.load (filepath: str , ...)
Load audio file into torch.Tensor object
将音频文件加载为Tensor

这里加载的tensor,形状为[1, length]

y1, sr = torchaudio.load(r'E:\adins\data\2s\test\cover\test60099_1.flac')

1.3 save

torchaudio.save (filepath: str , src: torch.Tensor , sample_rate: int , ...)
Save torch.Tensor object into an audio format
保存tensor到音频文件

save的参数很多,很难权衡参数的选择,这里推荐两种方式:

  • 使用默认参数

torchaudio.save(path, waveform, sample_rate)

根据官网的说法,你不提供encodeing的参数,save时也会自动选择

  • 以手中的音频作为依据,使用torchaudio.info的输出作为选择依据

# AudioMetaData(sample_rate=16000, num_frames=32000, num_channels=1, bits_per_sample=16, encoding=FLAC)
torchaudio.save(path, waveform, sample_rate, encoding="PCM_S", bits_per_sample=16)

值得注意的是,info输出的encoding严格来说是音频的format格式,save中的encoding是音频的编码方式,不能等同

  1. save的几个坑

2.1 save的实现后端

torchaudio.backend module provides implementations for audio file I/O functionalities, which are torchaudio.info, torchaudio.load, and torchaudio.save.
There are currently two implementations available.
* "sox_io" (default on Linux/macOS)
* "soundfile" (default on Windows)

save, load, info 的实现都是基于torchaudio.backend类,该类的后端(底层实现),在linux/Mac系统上是sox_io,在windows系统上依赖于soundfile。

在windows上使用IO函数之前要确保安装了soundfile

import soundfile as sf
print(sf.__version__)

还可以查看soundfile支持的音频格式

print(sf.available_formats())

2.2 save的format参数和encoding参数

format被测试过支持的参数有WAV、FLAC、OGG/VORBIS、SPHERE

encoding支持的参数有PCM_S, PCM_U 、PCM_F 、ULAW、ALAW

虽然这里描述flac支持这些encoding方式,但是当你同时使用时必然会报错

flac does not support encoding

这是因为在源码中,调用soundfile前,torchaudio用_get_subtype函数处理了encoding和format

可以看到,当format为flac时,不允许有encoding参数,否则就会报flac does not support encoding错误

也就是flac只支持PCM_S8、PCM_S16、PCM_S32三种格式,而且是根据bits_per_sample量化数做选择的

所以,想保存为flac格式的音频,应该使用format和bits_per_sample两个参数,而不使用encoding参数

  1. save的合法参数搭配

  • wav:

  • format、encoding、bits_per_sample

  • flac:

  • format、bits_per_sample

  • encoding、bits_per_sample

  • ogg/vorbis

  • format

  • sph

  • format

  • nis/nist

  • format

文档:

io函数APi :https://pytorch.org/audio/stable/torchaudio.html?highlight=torchaudio+info#torchaudio.info

backbone:https://pytorch.org/audio/stable/backend.html#overview

源码:https://pytorch.org/audio/stable/_modules/torchaudio/backend/soundfile_backend.html#save

猜你喜欢

转载自blog.csdn.net/qq_55796594/article/details/129306621
今日推荐