fix(audio): add offline audio resampling to match WebCodecs Opus 48kHz sample rate specification
This commit is contained in:
1 parent
f57be01310
commit
139bdf5fc7
1 file changed
+65
-30
+65
-30
@@ -1760,9 +1760,30 @@
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resamples an AudioBuffer to target sample rate using OfflineAudioContext (lossless sinc interpolation)
|
||||
*/
|
||||
async function resampleAudioBuffer(sourceBuffer, targetSampleRate) {
|
||||
if (!sourceBuffer || sourceBuffer.sampleRate === targetSampleRate) {
|
||||
return sourceBuffer;
|
||||
}
|
||||
const numChannels = Math.min(2, sourceBuffer.numberOfChannels);
|
||||
const targetLength = Math.max(1, Math.ceil(sourceBuffer.duration * targetSampleRate));
|
||||
const offlineCtx = new (window.OfflineAudioContext || window.webkitOfflineAudioContext)(
|
||||
numChannels,
|
||||
targetLength,
|
||||
targetSampleRate
|
||||
);
|
||||
const bufferSource = offlineCtx.createBufferSource();
|
||||
bufferSource.buffer = sourceBuffer;
|
||||
bufferSource.connect(offlineCtx.destination);
|
||||
bufferSource.start(0);
|
||||
return await offlineCtx.startRendering();
|
||||
}
|
||||
|
||||
/**
|
||||
* Hardware-Accelerated In-Browser Video Export Engine (WebCodecs + Muxer)
|
||||
* Supports: WebM VP9 Alpha & MP4 H.264 with robust codec probing
|
||||
* Supports: WebM VP9 Alpha & MP4 H.264 with robust codec probing & lossless audio
|
||||
*/
|
||||
async function exportVideoClientSide(format, targetWidth, targetHeight, fps, title, options = {}) {
|
||||
const isWebM = (format === 'webm_alpha');
|
||||
@@ -1811,6 +1832,7 @@
|
||||
let audioEncoder = null;
|
||||
let hasAudioTrack = false;
|
||||
let encoderError = null;
|
||||
let chosenAudioConfig = null;
|
||||
|
||||
// 2. Configure Muxer & Audio Encoder
|
||||
if (isWebM) {
|
||||
@@ -1818,7 +1840,6 @@
|
||||
throw new Error('WebMMuxer-Bibliothek wurde nicht geladen.');
|
||||
}
|
||||
|
||||
let audioConfig = null;
|
||||
if (typeof AudioEncoder !== 'undefined') {
|
||||
const audioTests = [
|
||||
{ codec: 'opus', sampleRate: 48000, numberOfChannels: numChannels, bitrate: 320000 },
|
||||
@@ -1828,7 +1849,7 @@
|
||||
try {
|
||||
const supported = await AudioEncoder.isConfigSupported(aCfg);
|
||||
if (supported && supported.supported) {
|
||||
audioConfig = supported.config || aCfg;
|
||||
chosenAudioConfig = supported.config || aCfg;
|
||||
break;
|
||||
}
|
||||
} catch (e) {}
|
||||
@@ -1846,24 +1867,27 @@
|
||||
alpha: supportsAlpha,
|
||||
frameRate: fps
|
||||
},
|
||||
audio: audioConfig ? {
|
||||
audio: chosenAudioConfig ? {
|
||||
codec: 'A_OPUS',
|
||||
numberOfChannels: audioConfig.numberOfChannels,
|
||||
sampleRate: audioConfig.sampleRate || sampleRate,
|
||||
numberOfChannels: chosenAudioConfig.numberOfChannels,
|
||||
sampleRate: chosenAudioConfig.sampleRate,
|
||||
bitrate: 320000
|
||||
} : undefined
|
||||
});
|
||||
|
||||
if (audioConfig) {
|
||||
if (chosenAudioConfig) {
|
||||
try {
|
||||
audioEncoder = new AudioEncoder({
|
||||
output: (chunk, meta) => muxer.addAudioChunk(chunk, meta),
|
||||
error: (e) => console.warn('AudioEncoder Warning:', e)
|
||||
error: (e) => {
|
||||
console.error('AudioEncoder Error:', e);
|
||||
encoderError = e;
|
||||
}
|
||||
});
|
||||
audioEncoder.configure(audioConfig);
|
||||
audioEncoder.configure(chosenAudioConfig);
|
||||
hasAudioTrack = true;
|
||||
} catch (e) {
|
||||
console.warn('AudioEncoder init failed, continuing without AudioEncoder:', e);
|
||||
console.error('AudioEncoder configure failed:', e);
|
||||
audioEncoder = null;
|
||||
hasAudioTrack = false;
|
||||
}
|
||||
@@ -1875,17 +1899,17 @@
|
||||
throw new Error('Mp4Muxer-Bibliothek wurde nicht geladen.');
|
||||
}
|
||||
|
||||
let audioConfig = null;
|
||||
if (typeof AudioEncoder !== 'undefined') {
|
||||
const audioTests = [
|
||||
{ codec: 'mp4a.40.2', sampleRate: sampleRate, numberOfChannels: numChannels, bitrate: 320000 },
|
||||
{ codec: 'mp4a.40.2', sampleRate: 48000, numberOfChannels: numChannels, bitrate: 320000 },
|
||||
{ codec: 'mp4a.40.2', sampleRate: 44100, numberOfChannels: numChannels, bitrate: 320000 }
|
||||
];
|
||||
for (const aCfg of audioTests) {
|
||||
try {
|
||||
const supported = await AudioEncoder.isConfigSupported(aCfg);
|
||||
if (supported && supported.supported) {
|
||||
audioConfig = supported.config || aCfg;
|
||||
chosenAudioConfig = supported.config || aCfg;
|
||||
break;
|
||||
}
|
||||
} catch (e) {}
|
||||
@@ -1899,24 +1923,27 @@
|
||||
width: targetWidth,
|
||||
height: targetHeight
|
||||
},
|
||||
audio: audioConfig ? {
|
||||
audio: chosenAudioConfig ? {
|
||||
codec: 'aac',
|
||||
numberOfChannels: audioConfig.numberOfChannels,
|
||||
sampleRate: audioConfig.sampleRate || sampleRate
|
||||
numberOfChannels: chosenAudioConfig.numberOfChannels,
|
||||
sampleRate: chosenAudioConfig.sampleRate
|
||||
} : undefined,
|
||||
fastStart: 'in-memory'
|
||||
});
|
||||
|
||||
if (audioConfig) {
|
||||
if (chosenAudioConfig) {
|
||||
try {
|
||||
audioEncoder = new AudioEncoder({
|
||||
output: (chunk, meta) => muxer.addAudioChunk(chunk, meta),
|
||||
error: (e) => console.warn('AAC AudioEncoder Warning:', e)
|
||||
error: (e) => {
|
||||
console.error('AAC AudioEncoder Error:', e);
|
||||
encoderError = e;
|
||||
}
|
||||
});
|
||||
audioEncoder.configure(audioConfig);
|
||||
audioEncoder.configure(chosenAudioConfig);
|
||||
hasAudioTrack = true;
|
||||
} catch (e) {
|
||||
console.warn('AAC AudioEncoder init failed, continuing without AudioEncoder:', e);
|
||||
console.error('AAC AudioEncoder configure failed:', e);
|
||||
audioEncoder = null;
|
||||
hasAudioTrack = false;
|
||||
}
|
||||
@@ -1934,30 +1961,34 @@
|
||||
|
||||
videoEncoder.configure(chosenVideoConfig);
|
||||
|
||||
// 4. Pre-encode Audio track if AudioEncoder is available
|
||||
if (audioEncoder && hasAudioTrack && audioEncoder.state === 'configured') {
|
||||
// 4. Encode Audio track synchronously with exact sample-rate matching
|
||||
if (audioEncoder && hasAudioTrack && audioEncoder.state === 'configured' && chosenAudioConfig) {
|
||||
try {
|
||||
exportStatusText.textContent = 'Encodiere Audio-Track in Studio-Qualität...';
|
||||
const totalSamples = state.audioBuffer.length;
|
||||
const channels = numChannels;
|
||||
const targetSampleRate = chosenAudioConfig.sampleRate || 48000;
|
||||
|
||||
// Resample AudioBuffer if needed (e.g. 44.1kHz -> 48kHz for Opus)
|
||||
const processedAudioBuffer = await resampleAudioBuffer(state.audioBuffer, targetSampleRate);
|
||||
const totalAudioSamples = processedAudioBuffer.length;
|
||||
const channels = chosenAudioConfig.numberOfChannels;
|
||||
const chunkSize = 4096;
|
||||
|
||||
for (let offset = 0; offset < totalSamples; offset += chunkSize) {
|
||||
for (let offset = 0; offset < totalAudioSamples; offset += chunkSize) {
|
||||
if (isExportCancelled) throw new Error('Export durch Benutzer abgebrochen');
|
||||
|
||||
const currentChunkSize = Math.min(chunkSize, totalSamples - offset);
|
||||
const currentChunkSize = Math.min(chunkSize, totalAudioSamples - offset);
|
||||
const chunkData = new Float32Array(currentChunkSize * channels);
|
||||
for (let c = 0; c < channels; c++) {
|
||||
const srcData = state.audioBuffer.getChannelData(c);
|
||||
const srcData = processedAudioBuffer.getChannelData(c);
|
||||
for (let i = 0; i < currentChunkSize; i++) {
|
||||
chunkData[c * currentChunkSize + i] = srcData[offset + i];
|
||||
}
|
||||
}
|
||||
|
||||
const timestampUs = Math.round((offset / sampleRate) * 1_000_000);
|
||||
const timestampUs = Math.round((offset / targetSampleRate) * 1_000_000);
|
||||
const audioData = new AudioData({
|
||||
format: 'f32-planar',
|
||||
sampleRate: sampleRate,
|
||||
sampleRate: targetSampleRate,
|
||||
numberOfChannels: channels,
|
||||
numberOfFrames: currentChunkSize,
|
||||
timestamp: timestampUs,
|
||||
@@ -1967,9 +1998,13 @@
|
||||
audioEncoder.encode(audioData);
|
||||
audioData.close();
|
||||
}
|
||||
|
||||
// Flush audio encoder to ensure all chunks are written into the muxer
|
||||
await audioEncoder.flush();
|
||||
console.log(`✅ Audio track successfully encoded & muxed (${totalAudioSamples} samples @ ${targetSampleRate}Hz)`);
|
||||
} catch (aErr) {
|
||||
console.warn('Audio pre-encode failed, skipping audio:', aErr);
|
||||
audioEncoder = null;
|
||||
console.error('Audio encoding failed:', aErr);
|
||||
throw new Error(`Fehler beim Audio-Encoding: ${aErr.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user