forked from watson-developer-cloud/python-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmicrophone-speech-to-text.py
More file actions
76 lines (57 loc) · 1.86 KB
/
Copy pathmicrophone-speech-to-text.py
File metadata and controls
76 lines (57 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# You need to install pyaudio to run this example
# pip install pyaudio
# Note that you need to record just once. You will not be able to send
# more audio after the initial recording.
from __future__ import print_function
import pyaudio
import tempfile
from watson_developer_cloud import SpeechToTextV1
from watson_developer_cloud.websocket import RecognizeCallback
speech_to_text = SpeechToTextV1(
username='YOUR SERVICE USERNAME',
password='YOUR SERVICE PASSWORD',
url='https://stream.watsonplatform.net/speech-to-text/api')
# Example using websockets
class MyRecognizeCallback(RecognizeCallback):
def __init__(self):
RecognizeCallback.__init__(self)
def on_transcription(self, transcript):
print(transcript)
def on_connected(self):
print('Connection was successful')
def on_error(self, error):
print('Error received: {}'.format(error))
def on_inactivity_timeout(self, error):
print('Inactivity timeout: {}'.format(error))
def on_listening(self):
print('Service is listening')
def on_transcription_complete(self):
print('Transcription completed')
def on_hypothesis(self, hypothesis):
print(hypothesis)
mycallback = MyRecognizeCallback()
tmp = tempfile.NamedTemporaryFile()
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 1024
RECORD_SECONDS = 5
audio = pyaudio.PyAudio()
stream = audio.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print('recording....')
with open(tmp.name, 'w') as f:
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
f.write(data)
stream.stop_stream()
stream.close()
audio.terminate()
print('Done recording...')
with open(tmp.name) as f:
speech_to_text.recognize_with_websocket(
audio=f, recognize_callback=mycallback)