이 튜토리얼에서는 Python으로 오디오 파일을 다루는 방법을 알아봅니다. 긴 오디오 파일을 여러 개의 청크(chunk)로 나눈 뒤, 각 청크의 내용을 인식하여 텍스트로 추출하고 결과를 텍스트 파일에 저장하는 과정까지 단계별로 살펴보겠습니다.
필요한 모듈 설치
먼저 아래 명령어로 필요한 모듈들을 설치합니다.
1. pydub 설치
pip install pydub
위 명령어를 실행하면 다음과 같은 성공 메시지가 출력됩니다.
Collecting pydub Downloading https://files.pythonhosted.org/packages/79/db/eaf620b73a1eec3c8c6f8f5 b0b236a50f9da88ad57802154b7ba7664d0b8/pydub-0.23.1-py2.py3-none-any.whl Installing collected packages: pydub Successfully installed pydub-0.23.1
2. audioread 설치
pip install audioread
실행 결과는 아래와 같습니다.
Collecting audioread Downloading https://files.pythonhosted.org/packages/2e/0b/940ea7861e0e9049f09dcfd 72a90c9ae55f697c17c299a323f0148f913d2/audioread-2.1.8.tar.gz Building wheels for collected packages: audioread Building wheel for audioread (setup.py): started Building wheel for audioread (setup.py): finished with status 'done' Created wheel for audioread: filename=audioread-2.1.8-cp37-none-any.whl size=2309 8 sha256=92b6f46d6b4726e7a13233dc9d84744ba74e23187123e67f663650f24390dc9d Stored in directory: C:\Users\hafeezulkareem\AppData\Local\pip\Cache\wheels\b9\64 \09\0b6417df9d8ba8bc61a7d2553c5cebd714ec169644c88fc012 Successfully built audioread Installing collected packages: audioread Successfully installed audioread-2.1.8
3. SpeechRecognition 설치
pip install SpeechRecognition
마찬가지로 실행하면 다음과 같은 메시지를 확인할 수 있습니다.
Collecting SpeechRecognition Downloading https://files.pythonhosted.org/packages/26/e1/7f5678cd94ec1234269d237 56dbdaa4c8cfaed973412f88ae8adf7893a50/SpeechRecognition-3.8.1-py2.py3-none-any.whl (32.8MB) Installing collected packages: SpeechRecognition Successfully installed SpeechRecognition-3.8.1
처리 과정 개요
전체 작업은 크게 두 단계로 진행됩니다.
오디오 파일을 일정한 크기의 청크로 분할합니다.
SpeechRecognition을 사용해 각 청크에서 음성 내용을 텍스트로 추출합니다.
이제 자신의 라이브러리에서 오디오 파일 하나를 준비하고 코드 작성을 시작해 보겠습니다.
예제 코드
# importing the module
import pydub
import speech_recognition
# getting the audio file
audio = pydub.AudioSegment.from_wav('audio.wav')
# length of the audio in milliseconds
audio_length = len(audio)
print(f'Audio Length: {audio_length}')
# chunk counter
chunk_counter = 1
audio_text = open('audio_text.txt', 'w+')
# setting where to slice the audio
point = 60000
# overlap - remaining audio after slicing
rem = 8000
# initialising variables to track chunks and ending
flag = 0
start = 0
end = 0
# iterating through the audio with incrementing of rem
for i in range(0, 2 * audio_length, point):
# in first iteration end = rem
if i == 0:
start = 0
end = point
else:
# other iterations
start = end - rem
end = start + point
# if end is greater than audio_length
if end >= audio_length:
end = audio_length
# to indicate stop
flag = 1
# getting a chunk from the audio
chunk = audio[start:end]
# chunk name
chunk_name = f'chunk_{chunk_counter}'
# storing the chunk to local storage
chunk.export(chunk_name, format = 'wav')
# printing the chunk
print(f'{chunk_name} start: {start} end: {end}')
# incrementing chunk counter
chunk_counter += 1
# recognising text from the audio
# initialising the recognizer
recognizer = speech_recognition.Recognizer()
# creating a listened audio
with speech_recognition.AudioFile(chunk_name) as chunk_audio:
chunk_listened = recognizer.listen(chunk_audio)
# recognizing content from the audio
try:
# getting content from the chunk
content = recognizer.recognize_google(chunk_listened)
# writing to the file
audio_text.write(content + '\n')
# if not recognized
except speech_recognition.UnknownValueError:
print('Audio is not recognized')
# internet error
except speech_recognition.RequestError as Error:
print("Can't connect to the internet")
# checking the flag
if flag == 1:
audio_text.close()
break코드 설명
코드의 핵심 로직을 간단히 정리하면 다음과 같습니다.
point = 60000: 한 번에 잘라낼 오디오 구간의 길이입니다. 단위는 밀리초(ms)이므로 60초에 해당합니다.
rem = 8000: 청크 사이에 8초씩 겹치도록 설정한 값입니다. 이렇게 하면 문장이 중간에 잘려서 인식률이 떨어지는 것을 방지할 수 있습니다.
flag 변수: 오디오의 끝에 도달했는지 확인하는 플래그로, 마지막 청크 처리 후 반복문을 종료하고 파일을 닫습니다.
recognize_google(): Google Speech Recognition API를 호출해 음성을 텍스트로 변환합니다. 이 기능은 인터넷 연결이 필요합니다.
실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Audio Length: 480052 chunk_1 start: 0 end: 60000 chunk_2 start: 52000 end: 112000 chunk_3 start: 104000 end: 164000 chunk_4 start: 156000 end: 216000 chunk_5 start: 208000 end: 268000 chunk_6 start: 260000 end: 320000 chunk_7 start: 312000 end: 372000 chunk_8 start: 364000 end: 424000 chunk_9 start: 416000 end: 476000 chunk_10 start: 468000 end: 480052
약 8분(480052ms) 길이의 오디오가 10개의 청크로 분할되었으며, 각 청크는 8초씩 겹쳐 있는 것을 확인할 수 있습니다.
변환된 텍스트 확인하기
생성된 텍스트 파일의 내용을 읽어 보겠습니다.
# opening the file in read mode
with open('audio_text.txt', 'r') as file:
print(file.read())실행하면 다음과 같이 오디오에서 추출된 텍스트가 출력됩니다.
English and I am here in San Francisco I am back in San Francisco last week we were in Texas at a teaching country and The Reader of the teaching conference was a plan e Re improve teaching as a result you are house backup file with bad it had some English is coming soon one day only time 12 o1 a.m. everything about her English now or powering on my email list sports in your city check your email email Harjeet girlfriend next Tuesday checking the year enjoying office English keep listening keep smiling keep enjoying your English learning
마무리
이번 튜토리얼에서는 Pydub로 긴 오디오 파일을 청크 단위로 분할하고, Google Speech Recognition API를 활용해 각 청크의 음성을 텍스트로 변환하는 방법을 배웠습니다. 이 방식은 팟캐스트, 강의 녹음 등 긴 오디오 콘텐츠를 자동으로 필기하거나 자막을 만들 때 유용하게 활용할 수 있습니다. 참고로 Google Speech Recognition API는 무료로 사용할 수 있지만 요청 횟수 제한이 있으므로, 대량의 오디오를 처리할 때는 주의가 필요합니다.
튜토리얼에 대해 궁금한 점이 있다면 댓글로 남겨주세요.