function loadAudio(postId, audioUrl, container, playOnLoad) { if (!postId…
- User
function loadAudio(postId, audioUrl, container, playOnLoad) { if (!postId || container.dataset.audioLoaded) return;
console.log('Cargando audio:', {postId, audioUrl}); const loadWithServiceWorker = async () => { try { if (navigator.serviceWorker.controller) { console.log('Usando Service Worker para cargar audio'); await window.we(postId, audioUrl, container, playOnLoad); } else { console.log('Service Worker no disponible, usando carga normal'); await window.we(postId, audioUrl, container, playOnLoad); } container.dataset.audioLoaded = 'true'; } catch (error) { console.error('Error cargando audio:', error); } }; loadWithServiceWorker();}
window.we = function (postId, audioUrl, container, playOnLoad = false) { // Verificaciones iniciales verifyAudioSettings();
if (!audioSettings || !audioSettings.nonce) { console.error('audioSettings no está configurado correctamente'); showError(container, 'Error de configuración'); return; } if (!window.wavesurfers) { window.wavesurfers = {}; } const MAX_RETRIES = 0; console.log(`Iniciando carga de audio - PostID: ${postId}`); function concatenateUint8Arrays(arrays) { let totalLength = arrays.reduce((acc, value) => acc + value.length, 0); let result = new Uint8Array(totalLength); let offset = 0; for (let array of arrays) { result.set(array, offset); offset += array.length; } return result; } async function loadAndPlayAudioStream(retryCount = 0) { try { window.audioLoading = true; const finalAudioUrl = buildAudioUrl(audioUrl, audioSettings.nonce); const response = await fetch(finalAudioUrl, { method: 'GET', credentials: 'same-origin', headers: { 'X-WP-Nonce': audioSettings.nonce, 'X-Requested-With': 'XMLHttpRequest', Accept: 'audio/mpeg', Range: 'bytes=0-' } }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const reader = response.body.getReader(); const iv = response.headers.get('X-Encryption-IV'); if (!iv) { throw new Error('No se recibió el IV en los encabezados de la respuesta'); } const ivArray = Uint8Array.from(atob(iv), c => c.charCodeAt(0)); let currentIV = ivArray; const contentLengthHeader = response.headers.get('Content-Length'); const contentLength = contentLengthHeader ? parseInt(contentLengthHeader) : -1; console.log(`Content-Length obtenido: ${contentLength}`); let buffer = new Uint8Array(0); let receivedLength = 0; // **Agrega esta línea para declarar decryptedChunks** let decryptedChunks = []; while (true) { const { done, value } = await reader.read(); console.log('Chunk leído:', { done, value }); if (done) { console.log('Transmisión completa'); break; } if (value && value.length > 0) { // Añadir los nuevos datos al buffer let tmp = new Uint8Array(buffer.length + value.length); tmp.set(buffer, 0); tmp.set(value, buffer.length); buffer = tmp; receivedLength += value.length; // Procesar el buffer let offset = 0; while (buffer.length - offset >= 4) { // Leer el prefijo de longitud const lengthView = new DataView(buffer.buffer, buffer.byteOffset + offset, 4); const chunkLength = lengthView.getUint32(0, false); // Big-endian // Verificar si tenemos suficientes datos para procesar el chunk if (buffer.length - offset >= 4 + chunkLength) { // Extraer los datos encriptados const encryptedData = buffer.subarray(offset + 4, offset + 4 + chunkLength); console.log('Procesando chunk:', { totalLength: buffer.byteLength, chunkLength: chunkLength, dataLength: encryptedData.byteLength }); try { // Desencriptar el chunk const decryptedData = await decryptAudioData(encryptedData, currentIV, audioSettings.key); decryptedChunks.push(new Uint8Array(decryptedData)); // Actualizar el IV (últimos 16 bytes de encryptedData) if (encryptedData.byteLength >= 16) { currentIV = encryptedData.subarray(encryptedData.byteLength - 16); } else { throw new Error('encryptedData es demasiado pequeño para obtener el IV'); } } catch (error) { console.error('Error desencriptando chunk:', error); throw error; } // Mover el offset más allá de este chunk offset += 4 + chunkLength; } else { // No tenemos suficientes datos aún break; } } // Eliminar los datos procesados del buffer if (offset > 0) { buffer = buffer.subarray(offset); } console.log(`Procesado ${receivedLength} bytes`); } } /* Tengo este problema aqui Procesando chunk: Object { totalLength: 20936, chunkLength: 8208, dataLength: 8208 } wavejs.js:347:37 Procesado 160540 bytes wavejs.js:383:29 Chunk leído: Object { done: true, value: undefined } wavejs.js:318:25 Transmisión completa wavejs.js:321:29 GET https://2upra.com/sample/jazzy-hammond-organ-sample/[object Blob] NS_BINDING_ABORTED Error en loadAndPlayAudioStream: error { target: audio, isTrusted: true, srcElement: audio, currentTarget: audio, eventPhase: 2, bubbles: false, cancelable: false, returnValue: true, defaultPrevented: false, composed: false, … } wavejs.js:404:21 Load error: error { target: audio, isTrusted: true, srcElement: audio, currentTarget: audio, eventPhase: 2, bubbles: false, cancelable: false, returnValue: true, defaultPrevented: false, composed: false, … } */ const audioBuffer = concatenateUint8Arrays(decryptedChunks); const audioBlob = new Blob([audioBuffer], { type: 'audio/mpeg' }); await validateAudio(audioBlob); const wavesurfer = initWavesurfer(container); window.wavesurfers[postId] = wavesurfer; await new Promise(resolve => { wavesurfer.once('ready', resolve); wavesurfer.load(blobUrl); }); handleWaveSurferEvents(wavesurfer, container, postId, blobUrl); } catch (error) { console.error('Error en loadAndPlayAudioStream:', error); handleLoadError(error, retryCount, container); } } - Assistant