medix-ai/www/html/_assets/js/audio.js

49 lines
1.5 KiB
JavaScript

async function cacheAudio(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const cache = await caches.open('audio-cache');
await cache.put(url, response.clone()); // Store a clone of the response
console.log(`Audio cached: ${url}`);
} catch (error) {
console.error(`Failed to cache audio: ${error}`);
}
}
async function getAudio(url) {
try {
const cache = await caches.open('audio-cache');
const cachedResponse = await cache.match(url);
if (cachedResponse) {
console.log(`Retrieving audio from cache: ${url}`);
return await cachedResponse.blob(); // Get the cached audio data
}
console.log(`Fetching audio from network: ${url}`);
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const blob = await response.blob();
await cache.put(url, response.clone()); // Update the cache
return blob;
} catch (error) {
console.error(`Failed to get audio: ${error}`);
}
}
// async function playCachedAudio(url) {
// const audioBlob = await getAudio(url);
// const audioUrl = URL.createObjectURL(audioBlob);
// const audio = new Audio(audioUrl);
// audio.onended = () => {
// URL.revokeObjectURL(audioUrl); // Clean up the URL object
// };
// audio.play();
// }