”’
!/usr/bin/env Python writes a code piece here
#-*-Coding:utf-8-*-
# @File: watsons2t.py
# @Author: Leonyan #
@Contact: http://blog.csdn.net/yl_1314 # @Date: 2016/9/7
# @Desc:
From Os.path import join, dirname
Import OS
Import Pyaudio
Import Wave
Import JSON
Import requests
From Watson_developer_cloud import SpeechToTextV1
From Watson_developer_cloud import TextToSpeechV1 a record of the voice to output.wav file use Pyaudio
Def recordvoice ():
CHUNK = 1024
FORMAT = pyaudio.paint16
channels = 2
RATE = 44100 record_seconds
= 5
wave_output_ FILENAME = "./resources/input.wav"
p = pyaudio. Pyaudio ()
stream = P.open (Format=format,
channels=channels,
rate=rate,
input=true,
Frames_ Per_buffer=chunk)
Print ("* recording")
frames = []
for I in range (0, int (rate/chunk * record_seconds)): C14/>data = Stream.read (CHUNK)
frames.append (data)
print ("* Done recording")
Stream.stop_stream ()
stream.close ()
p.terminate ()
wf = Wave.open (wave_output_filename, ' WB ')
Wf.setnchannels ( Channels)
Wf.setsampwidth (P.get_sample_size (FORMAT))
wf.setframerate (RATE)
wf.writeframes (b ". Join (frames))
wf.close ()
API for Speech to text service of Watson API on Bluemix
Def speech2text ():
Speech_to_text = SpeechToTextV1 (
Username= ' e008b1d6-6776-48aa-a107-e357e5396653 ',
Password= ' Shhxdf3fkznv ',
X_watson_learning_opt_out=false
)
# Print (Json.dumps (Speech_to_text.models (), indent=2))
# Print (Json.dumps speech_to_text.get_model (' En-us_ Broadbandmodel '), indent=2)
with open (Join (dirname (__file__), './resources/input.wav '),
' RB ') as Audio_ File:
# print ("speech to text: \ n"),
D1 = Json.dumps (speech_to_text.recognize (
audio_file, Content_type= ' Audio/wav ', timestamps=true,
word_confidence=true),
indent=2)
t1 = json.loads (d1)
Print t1[' results '][0][' alternatives '][0][' transcript '] return t1[' results '][0][' alternatives ' '][0]['
Transcript ']
Search result from Cloudant db on Bluemix
def searchinbluemix (strres):
Strtype= ""
Resu= "Sorry,i can not find any result!"
If ' money ' in Strres:
Strtype= "Money"
Elif "Books" in Strres:
Strtype= "Books"
Else
return resu
myurl = "https://e34abc18-91fd-438d-9501-a091cf6aa181-bluemix.cloudant.com/leondb/ 75375ea45fbd9dcaa5a13dd9120a7a85 "
resut = Json.dumps (Requests.get (Myurl). JSON (), indent=2)
t1 = json.loads ( Resut)
StrName = Strres.split () [ -1].lower ()
try:
Resu=t1[strtype][strname] return
resu
except : Return
resu
else: return
ResU
def text_2_speech (str):
Text_to_speech = TextToSpeechV1 (
Username= ' 944db649-faf1-436d-9f92-57ba85fff037 ',
Password= ' 06YVRGBVGRsH ',
x_watson_learning_opt_out=true) # Optional Flag
With open (Join (dirname (__file__), './resources/output.wav '),
' WB ') as Audio_file:
audio_file.write (
Text_to_speech.synthesize (str, accept= ' audio/wav ',
voice= "En-us_allisonvoice"))
CHUNK = 1024
WF = Wave.open (R './resources/output.wav ', ' RB ')
p = Pyaudio. Pyaudio ()
stream = P.open (Format=p.get_format_from_width (Wf.getsampwidth ()),
channels=wf.getnchannels (),
rate=wf.getframerate (),
output=true)
data = Wf.readframes (CHUNK) while
data!= ':
Stream.Write (data)
data = Wf.readframes (CHUNK)
stream.stop_stream ()
stream.close (
) P.terminate ()
Main function
Def startmain ():
Welcomestr= "Hi,what can I do for you?"
Print (WELCOMESTR)
Text_2_speech (WELCOMESTR) # #Welcom words
Recordvoice () # # # Record question content
Text_2_speech (Searchinbluemix (Speech2text)) # #search Coundat and fedback it by voice
Str1=raw_input ("Continue try again?") ( y/n) "). Upper () #try it again?
If str1== "Y":
# Recordvoice ()
# print Searchinbluemix (Speech2text ())
Startmain () elif
str1 = "N":
os._exit (0)
else:
print ("Input error,exit ...")
os._exit (0)
If name = = "Main":
Startmain ()