NHK NEWS WEBの主要ニュースRSSを定期的にチェックして新着があったら読み上げるやつ.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.189.0.min.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> | |
<script> | |
var intervalMs = 30000; // 何ミリ秒ごとに実行するか | |
var awsPollyRegion = 'ap-northeast-1'; // Amazon Pollyを実行するリージョン | |
var awsAccessKeyId = '〜IAMユーザーのアクセスキーID〜'; // IAMユーザーのアクセスキーID | |
var awsSecretAccessKey = '〜IAMユーザーのシークレットアクセスキー〜'; // IAMユーザーのシークレットアクセスキー | |
var lastParsedTime = 0; | |
var pollyParams = { | |
OutputFormat: "mp3", | |
SampleRate: "8000", | |
Text: '', | |
TextType: "text", | |
VoiceId: "Mizuki" | |
}; | |
AWS.config.update({accessKeyId: awsAccessKeyId, secretAccessKey: awsSecretAccessKey, region: awsPollyRegion}); | |
var polly = new AWS.Polly({apiVersion: '2016-06-10'}); | |
$(function(){ | |
setInterval(function(){ | |
exec(); // intervalMsで定義したmsごとに実行 | |
}, intervalMs); | |
}); | |
exec(); //初回実行 | |
function exec(){ | |
$.ajax({ | |
url: 'https://www3.nhk.or.jp/rss/news/cat0.xml', | |
dataType: 'xml', | |
success: function(res) { | |
var item = $(res).find('item'); | |
var title = item.find('title')[0].innerHTML; | |
var pubDate = item.find('pubDate')[0].innerHTML; | |
var pubDateMs = new Date(pubDate).getTime(); | |
if (pubDateMs > lastParsedTime) { | |
// ここで読み上げ | |
pollyParams.Text = title; | |
polly.synthesizeSpeech(pollyParams, function(err, data){ | |
if (err) console.log(err); | |
else console.log(data); | |
var audioElement = document.createElement('audio'); | |
audioElement.setAttribute('id', 'audioElement' + pubDateMs); | |
document.body.appendChild(audioElement); | |
var uInt8Array = new Uint8Array(data.AudioStream); | |
var blob = new Blob([uInt8Array.buffer]); | |
audioElement.src = URL.createObjectURL(blob); | |
audioElement.play(); | |
}); | |
console.log(title); | |
} | |
var lastParsedDate = new Date(); | |
lastParsedTime = lastParsedDate.getTime(); | |
console.log(lastParsedDate); | |
} | |
}); | |
} | |
</script> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment