Introdução ao PyDub

Processamento de Linguagem Falada em Python

Daniel Bourke

Machine Learning Engineer/YouTube Creator

Instalando o PyDub

$ pip install pydub
  • Se usar arquivos além de .wav, instale ffmpeg via ffmpeg.org
Processamento de Linguagem Falada em Python

Classe principal do PyDub: AudioSegment

# Importar a classe principal do PyDub
from pydub import AudioSegment
# Importar um arquivo de áudio
wav_file = AudioSegment.from_file(file="wav_file.wav", format="wav")
# Parâmetro format só para legibilidade
wav_file = AudioSegment.from_file(file="wav_file.wav")
type(wav_file)
pydub.audio_segment.AudioSegment
Processamento de Linguagem Falada em Python

Reproduzindo um arquivo de áudio

# Instalar simpleaudio para tocar wav
$pip install simpleaudio
# Importar a função play
from pydub.playback import play
# Importar arquivo de áudio
wav_file = AudioSegment.from_file(file="wav_file.wav")

# Reproduzir arquivo de áudio
play(wav_file)
Processamento de Linguagem Falada em Python

Parâmetros de áudio

# Importar arquivos de áudio
wav_file = AudioSegment.from_file(file="wav_file.wav")
two_speakers = AudioSegment.from_file(file="two_speakers.wav")

# Verificar número de canais wav_file.channels, two_speakers.channels
1, 2
wav_file.frame_rate
480000
Processamento de Linguagem Falada em Python

Parâmetros de áudio

# Obter o número de bytes por amostra
wav_file.sample_width
2
# Obter a amplitude máxima
wav_file.max
8488
Processamento de Linguagem Falada em Python

Parâmetros de áudio

# Duração do arquivo (ms)
len(wav_file)
3284
Processamento de Linguagem Falada em Python

Alterando parâmetros de áudio

# Alterar ATTRIBUTENAME de AudioSegment para x
changed_audio_segment = audio_segment.set_ATTRIBUTENAME(x)
# Alterar a largura da amostra para 1
wav_file_width_1 = wav_file.set_sample_width(1)
wav_file_width_1.sample_width
1
Processamento de Linguagem Falada em Python

Alterando parâmetros de áudio

# Alterar taxa de amostragem
wav_file_16k = wav_file.set_frame_rate(16000)
wav_file_16k.frame_rate
16000
# Alterar número de canais
wav_file_1_channel = wav_file.set_channels(1)
wav_file_1_channel.channels
1
Processamento de Linguagem Falada em Python

Vamos praticar!

Processamento de Linguagem Falada em Python

Preparing Video For Download...