LoginSignup
12
6

More than 5 years have passed since last update.

超絶簡単 TweetDeckをしゃべるクライアントに変える! (コード量: 254バイト)

Last updated at Posted at 2017-11-26

図1.png

作ったものの動画

以下のYouTubeの動画をご覧ください。
TweetDeckを喋れるようにした - YouTube

使い方

ブックマーク(ブックマークレット)を作成します。
以下の図のように、URLに以下の内容を入力します。
あとは、TweetDeckを開いて作成したブックマークをクリックするだけ。
(Chromeでのみ動作確認しています。)

URLの内容
javascript:(new MutationObserver(function(r){t=r[0].addedNodes[0].innerText.split("\n");if(!t[0].endsWith("Retweeted"))speechSynthesis.speak(new SpeechSynthesisUtterance(t.slice(3,-5).join("\n")))})).observe($(".chirp-container").get(0),{childList:true})

image.png

中身

まずSpeechSynthesisを使ってしゃべらせるテスト。

function speakText(text) {
  speechSynthesis.speak(
    new SpeechSynthesisUtterance(text)
  );
}

speakText("ブリブリブリブリュリュリュリュリュリュ!!!!!!ブツチチブブブチチチチブリリイリブブブブゥゥゥゥッッッ!!!!!!!");

これだけのコード量でしゃべってくれるのすごい。

次にTweetDeckのメインのタイムラインが変更(誰かがつぶやい)たら、検知する。MutationObserverを使うと簡単にできます。

var observer = new MutationObserver(function(mutationRecords, _observer) {
  var record = mutationRecords[0];
  var element = record.addedNodes[0];
  var text = element.innerText;
  var first_text = text.split("\n")[0];

  if (!first_text.endsWith("Retweeted")) {
    var tweet = text.split("\n").slice(3, -5).join("\n");
    console.log(tweet);
  }
});

var targetElement = $(".chirp-container").get(0);

observer.observe(targetElement, {
  childList: true
});

これらをつなぎ合わせる。

function speakText(text) {
  speechSynthesis.speak(
    new SpeechSynthesisUtterance(text)
  );
}

var observer = new MutationObserver(function(mutationRecords, _observer) {
  var record = mutationRecords[0];
  var element = record.addedNodes[0];
  var text = element.innerText;
  var first_text = text.split("\n")[0];

  if (!first_text.endsWith("Retweeted")) {
    var tweet = text.split("\n").slice(3, -5).join("\n");
    console.log(tweet);
    speakText(tweet);
  }
});

var targetElement = $(".chirp-container").get(0);

observer.observe(targetElement, {
  childList: true
});

短くすると以下のようになる。

(new MutationObserver(function(r){t=r[0].addedNodes[0].innerText.split("\n");if(!t[0].endsWith("Retweeted"))speechSynthesis.speak(new SpeechSynthesisUtterance(t.slice(3,-5).join("\n")))})).observe($(".chirp-container").get(0),{childList:true})

参考にしたサイト

ブラウザのみで音声認識とテキスト読み上げを実現する Web Speech API | CYOKODOG
動的に生成されるDOMの操作にsetTimeoutなんぞ使うな
SpeechSynthesis - Web API インターフェイス | MDN
MutationObserver - Web API インターフェイス | MDN

まとめ

テキスト読み上げすごい。MutationObserver簡単。

宣伝

フォローお願いします! :guitar: @redshoga

12
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
6