用Node.js操作Amazon Polly的示例脚本

ES6语法加油

描述声音

'use strict';

import aws from 'aws-sdk';
aws.config.loadFromPath('credential.json');

let polly = new aws.Polly({apiVersion: '2016-06-10',region:'us-west-2'});

// describeVoices
let descParams = {
    LanguageCode: 'ja-JP'
};

polly.describeVoices(descParams, (err, data)=>{
   if(err){
       console.log(err);
   } else {
       console.log(JSON.stringify(data))
   }
});

结果 (jié guǒ)

{"Voices":[{"Gender":"Female","Id":"Mizuki","LanguageCode":"ja-JP","LanguageName":"Japanese","Name":"Mizuki"}],"NextToken":null}

我可以毫无问题地获取到与CLI相同的结果。

合成语音

将其嵌套在回调函数中进行编写

let textMsg = 'パンツァーフォー';
       let speechParams = {
           OutputFormat: 'mp3',
           VoiceId: voiceId,
           Text: textMsg,
           SampleRate: '22050',
           TextType: 'text'
       };

       polly.synthesizeSpeech(speechParams).promise()
           .then(data => {
               console.log(data);
           })
           .catch(err => {
               console.log(err);
           });
       });

结果 – Jié guǒ

{ ContentType: 'audio/mpeg',
  RequestCharacters: '8',
  AudioStream: <Buffer 49 44 33 04 00 00 00 00 00 23 54 53 53 45 00 00 00 0f 00 00 03 4c 61 76 66 35 37 2e 34 31 2e 31 30 30 00 00 00 00 00 00 00 00 00 00 00 ff f3 60 c4 00 ... > }

我已经安全回来了。
要像在CLI中那样获取mp3文件。

polly.synthesizeSpeech(speechParams), (err, data) =>{
    .then(data => {
        console.log(data);
        fs.writeFile('audio/polly.mp3', data.AudioStream, (err) => {
            if (err) {
                console.log(err);
            } else {
                console.log('Success');
            }
        })
    })
    .catch(err => {
        console.log(err);
    });
});

这样做的话,它会掉在我手里。

总结

在使用SDK时,与CLI相比,这种服务并不太复杂。
实际上,将下载的内容上传到S3并进行一些操作会更好吗?

整个脚本

'use strict';

const aws = require('aws-sdk');
const fs = require('fs');

aws.config.loadFromPath('<クレデンシャルへのパス>');
let polly = new aws.Polly({apiVersion: '2016-06-10',region:'us-west-2'});


// describeVoices
let descParams = {
    LanguageCode: 'ja-JP'
};

polly.describeVoices(descParams)
    .then(data => {
        //console.log(JSON.stringify(data));
        let voiceId = data.Voices[0].Id;

        // synthesizeSpeech
        let textMsg = 'あんずのうた';
        let speechParams = {
            OutputFormat: 'mp3',
            VoiceId: voiceId,
            Text: textMsg,
            SampleRate: '22050',
            TextType: 'text'
        };

        return polly.synthesizeSpeech(speechParams).promise();
    })
    .then(data => {
        console.log(data);
        fs.writeFile('polly.mp3', data.AudioStream, (err) => {
            if (err) {
                console.log(err);
            } else {
                console.log('Success');
            }
        });
    })
    .catch(err => {
        console.log(err);
    });
});

请注意

广告
将在 10 秒后关闭
bannerAds