Skip to content

Instantly share code, notes, and snippets.

@ggorlen
Created March 24, 2019 23:08
Show Gist options
  • Save ggorlen/04cd13b1f6e4c8347684be69c64322e1 to your computer and use it in GitHub Desktop.
Save ggorlen/04cd13b1f6e4c8347684be69c64322e1 to your computer and use it in GitHub Desktop.
Transcribe speech using the Google Speech Recognition API
"""
Transcribe speech using the Google Speech Recognition API
"""
import math
import speech_recognition
import sys
if len(sys.argv) < 2:
print("usage: python3 transcribe.py speech_file.wav output_file.txt")
sys.exit(0)
filename = sys.argv[1]
chunk_size_s = 60
recognizer = speech_recognition.Recognizer()
audio_file = speech_recognition.AudioFile(filename)
text = []
with audio_file as source:
for i in range(0, math.floor(source.DURATION), chunk_size_s):
duration = chunk_size_s
if i + chunk_size_s > source.DURATION:
duration = source.DURATION - i
audio = recognizer.record(source, offset=i, duration=duration)
try:
text.append(recognizer.recognize_google(audio))
except speech_recognition.UnknownValueError as e:
print(e)
with open(sys.argv[2] if len(sys.argv) > 2 else "output.txt", "w") as f:
f.write("".join(text))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment