Bunpro: Example Sentence Audio

Adds Google Translate audio to all the sentences that do not yet have audio.

  1. // ==UserScript==
  2. // @name Bunpro: Example Sentence Audio
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.1.7
  5. // @description Adds Google Translate audio to all the sentences that do not yet have audio.
  6. // @author Kumirei
  7. // @include *bunpro.jp/*
  8. // @exclude *community.bunpro.jp*
  9. // @require https://greasyfork.org/scripts/432418-wait-for-selector/code/Wait%20For%20Selector.js?version=974366
  10. // @grant none
  11. // ==/UserScript==
  12.  
  13. (function($, wfs) {
  14. // Need to remove the referrer; otherwise returns 404s
  15. var remRef = document.createElement('meta');
  16. remRef.name = 'referrer';
  17. remRef.content = 'same-origin';
  18. document.querySelector('head').append(remRef);
  19.  
  20. // CSS stuff
  21. $('head').append('<style>audio.TTS {margin-top: 6px; border: 1px solid white !important; border-radius: 28px !important;}</style>');
  22.  
  23. // The player element
  24. var first = "<div class=\"audio-holder\">" +
  25. " <audio class=TTS controls >" +
  26. " <source src=\"https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&q=";
  27. var last = " &tl=ja&total=1&idx=0?\" type=\"audio/mpeg\">" +
  28. " </audio>" +
  29. "</div>";
  30.  
  31. // Detect context sentences
  32. wfs.wait('.japanese-example-sentence', function(e) {
  33. // Do nothing if there is already audio provided
  34. if (e[0].nextElementSibling.className != "audio-holder" || e[0].nextElementSibling.innerText.includes('coming soon')) {
  35. // Get sentence in plain text and add the player
  36. var sentence = parseSentence(e[0]);
  37. e.after(first + sentence + last);
  38. }
  39. });
  40.  
  41. // Extract the sentence from the element
  42. function parseSentence(sentenceElem) {
  43. var sentence = "";
  44. sentenceElem.childNodes.forEach(function(elem) {
  45. // find the text in each kind of element and append it to the sentence string
  46. var name = elem.nodeName;
  47. if (name == "#text") {
  48. sentence += elem.data;
  49. }
  50. else if (name == "STRONG" || name == "SPAN") {
  51. if (name == "STRONG" && elem.children.length) {
  52. sentence += elem.children[0].childNodes[0].data; // with kanji in url
  53. //sentence += elem.children[0].children[1].innerText; // with kana in url
  54. }
  55. else {
  56. sentence += elem.innerText;
  57. }
  58. }
  59. else if (name == "RUBY") {
  60. sentence += elem.childNodes[0].data; // with kanji in url
  61. //sentence += elem.children[1].innerText; // with kana in url
  62. }
  63. });
  64. return sentence;
  65. }
  66. })(window.jQuery, window.wfs);