Nin*_*pac 10 javascript audio html5 amazon-web-services amazon-polly
这是我的脚本:
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.13.min.js"></script>
<script>
AWS.config.region = 'eu-west-1';
AWS.config.accessKeyId = 'FOO';
AWS.config.secretAccessKey = 'BAR';
var polly = new AWS.Polly({apiVersion: '2016-06-10'});
var params = {
OutputFormat: 'mp3', /* required */
Text: 'Hello world', /* required */
VoiceId: 'Joanna', /* required */
SampleRate: '22050',
TextType: 'text'
};
polly.synthesizeSpeech(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
</script>
Run Code Online (Sandbox Code Playgroud)
请求成功,我得到了这样的回复:
我该如何使用这种回复?我知道响应是反序列化的音频,但我如何实际播放它,比如说,在HTML5音频元素中?
此外,这个答案解释了为什么这种类型的阵列适合音频数据:https://stackoverflow.com/a/26320913/1325575
Ell*_*ott 18
var uInt8Array = new Uint8Array(audioStream);
var arrayBuffer = uInt8Array.buffer;
var blob = new Blob([arrayBuffer]);
var url = URL.createObjectURL(blob);
audioElement.src = url;
audioElement.play();
Run Code Online (Sandbox Code Playgroud)
我创建了一个名为ChattyKathy的Javascript库,如果你想采取简单的方法,它将为你处理整个过程.
只需传递一个AWS Credentials对象,然后告诉她该说些什么.她将调用AWS,转换响应并播放音频.
var settings = {
awsCredentials: awsCredentials,
awsRegion: "us-west-2",
pollyVoiceId: "Justin",
cacheSpeech: true
}
var kathy = ChattyKathy(settings);
kathy.Speak("Hello world, my name is Kathy!");
kathy.Speak("I can be used for an amazing user experience!");
Run Code Online (Sandbox Code Playgroud)
Elliott 的 Chatty Kathy 代码对我来说效果很好,但是 Safari 和移动有两个不同的问题。
Safari:创建 blob 时,必须指定内容类型:
var blob = new Blob([arrayBuffer], {type: 'audio/mpeg'});
url = webkitURL.createObjectURL(blob);
Run Code Online (Sandbox Code Playgroud)
Mobile:以上肯定是真的,而且播放需要由用户触摸事件发起。注意:较旧的 iOS 版本似乎要求在与触摸事件相同的线程中启动播放,因此启动最终调用 audio.play() 的承诺链的触摸事件将失败。后来的 iOS 版本在这方面似乎更聪明。