In this tutorial, we will introduce you how to read an audio with specific sampling rate in torchaudio. It is very useful for audio processing.
How to load an audio with specific sampling rate in torchaudio?
Here are two steps:
Step 1: load an audio
We can use torchaudio.load() function to load an audio. Here is the tutorial:
Understand torchaudio.load(): Read Audio with Examples – TorchAudio Tutorial
Step 2: resampling an audio
We can use torchaudio.functional.resample() to resample an audio. Here is the detail.
TorchAudio Audio Resampling Tutorial for Beginners
Here we will create a function to implement it.
import torchaudio wav_file = "008554.wav" def read_audio(wav_file, sample_rate = 8000): wav_data, sr = torchaudio.load(wav_file) print(wav_data.shape) if sr != sample_rate: wav_data_2 = torchaudio.functional.resample(wav_data, sr, sample_rate) print(wav_data_2.shape) return wav_data_2 wav_data_2 = read_audio(wav_file)
Run this code, we will see:
torch.Size([1, 230496]) torch.Size([1, 38416])