ในบทช่วยสอนนี้ เราจะทำงานกับไฟล์เสียง (Audio Files) โดยการแบ่งเสียงเป็นชิ้นๆ (chunks) เพื่อทำการแปลงเสียงเป็นข้อความ (Speech Recognition) และบันทึกผลลัพธ์ลงในไฟล์ข้อความ
ติดตั้งโมดูลที่จำเป็น
pip install pydub pip install audioread pip install SpeechRecognition
ขั้นตอนการทำงาน
- การแบ่งเสียงเป็น chunks - ตัดไฟล์เสียงยาวเป็นชิ้นเล็กๆ
- การแปลงเสียงเป็นข้อความ - ใช้ SpeechRecognition ร่วมกับ Google Speech Recognition API
ตัวอย่างโค้ด
import pydub
import speech_recognition
# getting the audio file
audio = pydub.AudioSegment.from_wav('audio.wav')
# length of audio in milliseconds
audio_length = len(audio)
print(f'Audio Length: {audio_length}')
chunk_counter = 1
audio_text = open('audio_text.txt', 'w+')
# slice point: 60 seconds = 60000 ms
point = 60000
# overlap: 8 seconds = 8000 ms
rem = 8000
flag = 0
start = 0
end = 0
for i in range(0, 2 * audio_length, point):
if i == 0:
start = 0
end = point
else:
start = end - rem
end = start + point
if end >= audio_length:
end = audio_length
flag = 1
# get chunk
chunk = audio[start:end]
chunk_name = f'chunk_{chunk_counter}'
# export chunk
chunk.export(chunk_name, format='wav')
print(f'{chunk_name} start: {start} end: {end}')
chunk_counter += 1
# speech recognition
recognizer = speech_recognition.Recognizer()
with speech_recognition.AudioFile(chunk_name) as chunk_audio:
chunk_listened = recognizer.listen(chunk_audio)
try:
content = recognizer.recognize_google(chunk_listened)
audio_text.write(content + '\n')
except speech_recognition.UnknownValueError:
print('Audio is not recognized')
except speech_recognition.RequestError as Error:
print("Can't connect to the internet")
if flag == 1:
audio_text.close()
breakผลลัพธ์การแบ่ง Chunk
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
เนื้อหาไฟล์ข้อความที่ได้
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
สรุป
โค้ดนี้สาธิตการแบ่งไฟล์เสียงยาวเป็น chunks พร้อม overlap เพื่อไม่ให้ตัดคำพูดกลางคัน และใช้ Google Speech Recognition API ผ่านไลบรารี SpeechRecognition หากมีข้อสงสัย สามารถถามได้ในส่วนความคิดเห็น