Advertisement
Guest User

Read text using voicevox

a guest
Feb 13th, 2023
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name        Read Everything
  3. // @namespace   Violentmonkey Scripts
  4. // @include     *
  5. // @grant       none
  6. // @version     1.0
  7. // @author      -
  8. // ==/UserScript==
  9.  
  10. // requires voicevox to be running, eg
  11. // C:\Users\<youruser>\AppData\Local\Programs\VOICEVOX\run.exe --host localhost --cors_policy_mod all
  12.  
  13. const host = 'http://localhost:50021'
  14. const speaker = 0
  15.  
  16. document.body.addEventListener("keydown", (e) => {
  17.   if (!(e.shiftKey && e.altKey)) return
  18.   const text = getSelectionText()
  19.   if (!text) return
  20.   play(text)
  21. })
  22.  
  23. const play = async (text) => {
  24.   const audioQuery = await fetch(`${host}/audio_query?text=${text}&speaker=${speaker}`, {
  25.     "method": "POST"
  26.   })
  27.   const meta = await audioQuery.json()
  28.  
  29.   const maybeWav = await fetch(`${host}/synthesis?speaker=${speaker}`, {
  30.     "headers": {
  31.       "content-type": "application/json",
  32.     },
  33.     "body": JSON.stringify(meta),
  34.     "method": "POST",
  35.   })
  36.   const buffer = await maybeWav.arrayBuffer()
  37.   const audioContext = new(window.AudioContext || window.webkitAudioContext)()
  38.   const decodedAudio = await audioContext.decodeAudioData(buffer)
  39.   const gain = audioContext.createGain()
  40.   gain.connect(audioContext.destination)
  41.   const playSound = audioContext.createBufferSource()
  42.   playSound.buffer = decodedAudio
  43.   playSound.connect(gain)
  44.   playSound.start(0)
  45. }
  46.  
  47. const getSelectionText = () => {
  48.   let text = ""
  49.   if (window.getSelection) {
  50.     text = window.getSelection().toString()
  51.   } else if (document.selection && document.selection.type != "Control") {
  52.     text = document.selection.createRange().text
  53.   }
  54.   return text;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement