-
Notifications
You must be signed in to change notification settings - Fork 0
/
txt2speech_tofile.py
executable file
·69 lines (59 loc) · 2.41 KB
/
txt2speech_tofile.py
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
"""Getting Started Example for Python 2.7+/3.3+"""
from boto3 import Session
from botocore.exceptions import BotoCoreError, ClientError
from contextlib import closing
import os
import sys
import subprocess
from tempfile import gettempdir
# Create a client using the credentials and region defined in the [adminuser]
# section of the AWS credentials file (~/.aws/credentials).
session = Session(profile_name="adminuser")
polly = session.client("polly")
phrase_json = {'text': ["Turn off the lights, please."], 'voiceId': ['Salli'], 'outputFormat': ['ogg_vorbis']}
myText = "Alexa, " + phrase_json.get("text")[0]
myVoiceId = phrase_json.get("voiceId")[0]
#myText="Alexa, what are some of your skills?"
#myText="Turn off the lights, please. And then turn up the music!"
#myVoiceId="Brian"
#myVoiceId="Joey"
#myVoiceId="Amy"
#myVoiceId="Salli"
#myVoiceId="Kendra"
#myVoiceId="Justin"
try:
# Request speech synthesis
response = polly.synthesize_speech(Text=myText, OutputFormat="mp3",
VoiceId=myVoiceId)
except (BotoCoreError, ClientError) as error:
# The service returned an error, exit gracefully
print(error)
sys.exit(-1)
# Access the audio stream from the response
if "AudioStream" in response:
# Note: Closing the stream is important as the service throttles on the
# number of parallel connections. Here we are using contextlib.closing to
# ensure the close method of the stream object will be called automatically
# at the end of the with statement's scope.
with closing(response["AudioStream"]) as stream:
output = os.path.join(gettempdir(), "speech.mp3")
try:
# Open a file for writing the output as a binary stream
#with open(output.mp3", "wb") as file:#write to variable
with open(output, "wb") as file:# write to file
file.write(stream.read())
except IOError as error:
# Could not write to file, exit gracefully
print(error)
sys.exit(-1)
else:
# The response didn't contain audio data, exit gracefully
print("Could not stream audio")
sys.exit(-1)
# Play the audio using the platform's default player
if sys.platform == "win32":
os.startfile(output)
else:
# the following works on Mac and Linux. (Darwin = mac, xdg-open = linux).
opener = "open" if sys.platform == "darwin" else "xdg-open"
subprocess.call(['/usr/bin/afplay', output])