Created
April 18, 2025 20:35
-
-
Save zefanjajobse/1b91313557b4dae27e0fce72e4db37fb to your computer and use it in GitHub Desktop.
Use browser SpeechRecognition to send closed captions to youtube livestream
This file contains hidden or 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
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Document</title> | |
| <script type="text/javascript" src="https://livejs.com/live.js"></script> | |
| </head> | |
| <body> | |
| test | |
| <div id="result"></div> | |
| <div id="temp"></div> | |
| <script> | |
| const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; | |
| const recognition = new SpeechRecognition(); | |
| recognition.continuous = true; | |
| recognition.interimResults = true; | |
| recognition.lang = "nl-NL" | |
| recognition.onerror = function (event) { | |
| console.log(event); | |
| if (event.error === 'network') { | |
| if (!navigator.onLine) { | |
| message = 'No internet connection. Its required for speech recognition.'; | |
| } else { | |
| message = `Speech recognition is unavailable.`; | |
| } | |
| } | |
| }; | |
| recognition.start(); | |
| let counter = 1; | |
| recognition.onresult = function (e) { | |
| let final_transcript = ''; | |
| for (let i = e.resultIndex; i < e.results.length; ++i) { | |
| const transcript = e.results[i][0].transcript; | |
| if (e.results[i].isFinal) { | |
| final_transcript = transcript; | |
| document.getElementById("result").innerHTML += `<div>${transcript}</div>`; | |
| document.getElementById("temp").innerHTML = ""; | |
| } else { | |
| document.getElementById("temp").innerHTML = `<div>${transcript}</div>`; | |
| } | |
| } | |
| if (final_transcript) { | |
| console.log(final_transcript.trim()); | |
| } | |
| var payload = new Date().toISOString().replace("Z", "") + " region:reg1#cue1\n " + final_transcript.trim() + "\n"; | |
| const url = "http://upload.youtube.com/closedcaption?cid=YOUTUBE_CID"; | |
| const api_req = fetch(`${url}&seq=${counter}`, { | |
| mode: 'no-cors', | |
| maxBodyLength: Infinity, | |
| method: "post", | |
| body: payload, | |
| headers: { "Content-type": "text/plain" }, | |
| }); | |
| api_req.then((res) => { | |
| console.log(res.status); | |
| res.text().then((e) => { | |
| console.log(e) | |
| }) | |
| }) | |
| counter += 1; | |
| }; | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment