gpt4 book ai didi

javascript - 使用Mediarecorder无需保存AudioBuffer

转载 作者:行者123 更新时间:2023-12-03 12:22:47 25 4
gpt4 key购买 nike

我将两个AudioBuffer合并为一个。
在我看来,这无需使用MediaRecorder就可以实现,因为我不需要实时记录。
这就是我现在要做的:

concatAudio(buffers: AudioBuffer[]): void {
const totalLength = buffers.reduce((acc, buffer) => acc + buffer.length, 0);
const audioContext = new AudioContext();
const audioBuffer = audioContext.createBuffer(1, totalLength, 48000);
const src = audioContext.createBufferSource();
const dst = audioContext.createMediaStreamDestination();

let offset = 0;
buffers.map((buffer) => {
audioBuffer.getChannelData(0).set(buffer.getChannelData(0), offset);
offset += buffer.length;
});

src.buffer = audioBuffer;
src.connect(dst);
src.start();

this.recordAudio(dst.stream, audioBuffer.duration);
}
recordAudio()中,我将流输入到 MediaRecorder中。
现在录制新的流所花的时间与按顺序播放的两个 Audiobuffer的持续时间一样长...
还有另一种方法吗?
谢谢。

最佳答案

嗯,有一种[实验性的方法]可以并行记录缓冲区并粘上 Blob 。您可以根据需要将音频缓冲区分成多个块,并受最小块长度的限制。在Chrome中有效,在FF中无效。
在任何情况下都不要使用它。 (From gist)。

// try splitting buffer to N parts, recording in parallel, generating blob
async function recordParallel() {
const audioContext = new AudioContext();

const bufs = [], all = []
for (let i = 0; i < 10; i++ ) {
// 2705 - min chunk length for opus encoder in Chrome, so we increase block size to 4096 plus silent header
let buf = new AudioBuffer({length: 4096, sampleRate: audioContext.sampleRate})
bufs.push(buf)
let data = buf.getChannelData(0)
for (let j = 0; j < 4096; j++) data[j] = Math.sin(j / ((i + 1) * 2))

// create recorders
const source = audioContext.createBufferSource();
source.buffer = buf;


const chunks = []
all.push(new Promise(r => {
const dest = audioContext.createMediaStreamDestination();
const recorder = new MediaRecorder(dest.stream);
source.connect(dest)

recorder.start(10)
// delay is needed to shift encodingblocks
source.start(0)

recorder.ondataavailable = (e) => {
const blob = e.data
if (blob.size) chunks.push(blob)
}
recorder.onstop = e => {
r(chunks)
}
source.onended = e => {
recorder.stop()
}
}))
}

const blobs = await Promise.all(all);

// combine multiple recorders back
console.log(blobs)
var blob = new Blob([...blobs[0], ...blobs.slice(1).map(b => b.slice(1)).flat()], { 'type' : 'audio/ogg; codecs=opus' });
let audio = document.createElement('audio')
audio.src = URL.createObjectURL(blob);
audio.play()
}

关于javascript - 使用Mediarecorder无需保存AudioBuffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63686468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com