Created
June 18, 2024 10:46
-
-
Save adamziel/3ae0301c2a1318a7943d473367767c97 to your computer and use it in GitHub Desktop.
Reag page using OpenAI API
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
async function fetchAudioBlob(textContent) { | |
const myHeaders = new Headers(); | |
myHeaders.append("Authorization", "Bearer TOKEN-HERE"); // Add your actual API key here | |
myHeaders.append("Content-Type", "application/json"); | |
const raw = JSON.stringify({ | |
"model": "tts-1", | |
"input": textContent, | |
"voice": "alloy" | |
}); | |
const requestOptions = { | |
method: "POST", | |
headers: myHeaders, | |
body: raw, | |
redirect: "follow" | |
}; | |
const response = await fetch("https://api.openai.com/v1/audio/speech", requestOptions); | |
if (!response.ok) { | |
throw new Error('Network response was not ok ' + response.statusText); | |
} | |
return await response.blob(); | |
} | |
async function playAudio(blob) { | |
const audioUrl = URL.createObjectURL(blob); | |
const audio = new Audio(audioUrl); | |
audio.playbackRate = 1.2; | |
await new Promise((resolve, reject) => { | |
audio.onended = resolve; | |
audio.onerror = reject; | |
audio.play(); | |
}); | |
URL.revokeObjectURL(audioUrl); // Clean up the object URL after playing | |
} | |
async function processElements() { | |
const elements = document.querySelectorAll('.o2-post .entry-content > *'); | |
let nextAudioBlob = null; | |
let nextElementIndex = 0; | |
async function preloadNextAudio() { | |
while (nextElementIndex < elements.length) { | |
const textContent = elements[nextElementIndex].textContent.trim(); | |
nextElementIndex++; | |
if (textContent) { | |
return fetchAudioBlob(textContent); | |
} | |
} | |
return null; | |
} | |
nextAudioBlob = await preloadNextAudio(); // Preload the first audio | |
while (nextAudioBlob) { | |
const currentAudioBlob = nextAudioBlob; | |
const preloadPromise = preloadNextAudio(); // Start preloading the next audio | |
await playAudio(currentAudioBlob); // Play the current audio | |
nextAudioBlob = await preloadPromise; // Wait for the next audio to be preloaded | |
} | |
} | |
// Start processing | |
processElements(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment