castv2-clientのインストール
castv2-clientをインストールします。
npm install castv2-client
Windowsの場合は、
npm install castv2-client --no-optional
google-tts-apiのインストール
google-tts-apiをインストールします。
npm install google-tts-api --save
Google Homeに話をさせるプログラム
Google Homeに話をさせるプログラムです。
環境に合わせて、変数ipの値を変更してください。
// Google-HomeのIPアドレス
const ip = '192.168.97.2';
次の変数を変更することで、話す言葉を変更できます。
Google TTS APIの制限により、変数textは最大200文字までです。
// 読み上げる文字列
const text = 'こんにちは';
// 言語
const lang = 'ja-JP';
// 読み上げ速度
const speed = 1;
以下、プログラムです。
const googleTTS = require('google-tts-api');
const Client = require('castv2-client').Client;
const DefaultMediaReceiver = require('castv2-client').DefaultMediaReceiver;
// 読み上げる文字列
const text = 'こんにちは';
// 言語
const lang = 'ja-JP';
// 読み上げ速度
const speed = 1;
// Google-HomeのIPアドレス
const ip = '192.168.97.2';
const get_TTS_URL = (text, lang, speed) => {
return googleTTS(text, lang, speed).then(function (url) {
return url;
}).catch(function (err) {
console.error(err.stack);
return '';
});
};
const say = (host, content) => {
const client = new Client();
client.connect(host, function () {
client.launch(DefaultMediaReceiver, function (err, player) {
if (err) {
console.log(err);
return;
}
player.on('status', function (status) {
console.log(`status broadcast playerState=${status.playerState}`);
});
const media = {
contentId: content,
contentType: 'audio/mp3',
streamType: 'BUFFERED'
};
player.load(media, { autoplay: true }, function (err, status) {
client.close();
});
});
});
client.on('error', function (err) {
console.log(`Error: ${err.message}`);
client.close();
});
};
async function main() {
const url = await get_TTS_URL(text, lang, speed);
if (url == '') return;
say(ip, url);
}
main();