我有一个实时,恒定的波形数据源,它为我提供了第二个单通道音频,每秒采样率恒定。目前我以这种方式玩它们:
// data : Float32Array, context: AudioContext
function audioChunkReceived (context, data, sample_rate) {
var audioBuffer = context.createBuffer(2, data.length, sample_rate);
audioBuffer.getChannelData(0).set(data);
var source = context.createBufferSource(); // creates a sound source
source.buffer = audioBuffer;
source.connect(context.destination);
source.start(0);
}
音频播放正常,但正在播放的连续块之间有明显的暂停(如预期的那样)。我想摆脱它们,我理解我必须引入某种缓冲。
问题:
答案 0 :(得分:4)
您没有显示audioChunkReceived
的方式,但为了获得无缝播放,您必须确保在播放之前拥有数据,并且之前的停止播放
一旦你有了这个,你可以通过调用start(t)安排最新的块开始播放,前一个块结束,其中t是前一个块的结束时间。
但是,如果缓冲区采样率与context.sampleRate不同,则由于将缓冲区转换为上下文速率所需的重新采样,它可能无法顺利播放。
答案 1 :(得分:4)
我已经在TypeScript中编写了一个小类,现在用作缓冲区。它具有 bufferSize ,用于控制它可以容纳多少块。它简短且具有自我描述性,因此我将其粘贴到此处。有很多改进,所以欢迎任何想法。
(您可以使用:https://www.typescriptlang.org/play/)
快速将其转换为JSclass SoundBuffer {
private chunks : Array<AudioBufferSourceNode> = [];
private isPlaying: boolean = false;
private startTime: number = 0;
private lastChunkOffset: number = 0;
constructor(public ctx:AudioContext, public sampleRate:number,public bufferSize:number = 6, private debug = true) { }
private createChunk(chunk:Float32Array) {
var audioBuffer = this.ctx.createBuffer(2, chunk.length, this.sampleRate);
audioBuffer.getChannelData(0).set(chunk);
var source = this.ctx.createBufferSource();
source.buffer = audioBuffer;
source.connect(this.ctx.destination);
source.onended = (e:Event) => {
this.chunks.splice(this.chunks.indexOf(source),1);
if (this.chunks.length == 0) {
this.isPlaying = false;
this.startTime = 0;
this.lastChunkOffset = 0;
}
};
return source;
}
private log(data:string) {
if (this.debug) {
console.log(new Date().toUTCString() + " : " + data);
}
}
public addChunk(data: Float32Array) {
if (this.isPlaying && (this.chunks.length > this.bufferSize)) {
this.log("chunk discarded");
return; // throw away
} else if (this.isPlaying && (this.chunks.length <= this.bufferSize)) { // schedule & add right now
this.log("chunk accepted");
let chunk = this.createChunk(data);
chunk.start(this.startTime + this.lastChunkOffset);
this.lastChunkOffset += chunk.buffer.duration;
this.chunks.push(chunk);
} else if ((this.chunks.length < (this.bufferSize / 2)) && !this.isPlaying) { // add & don't schedule
this.log("chunk queued");
let chunk = this.createChunk(data);
this.chunks.push(chunk);
} else { // add & schedule entire buffer
this.log("queued chunks scheduled");
this.isPlaying = true;
let chunk = this.createChunk(data);
this.chunks.push(chunk);
this.startTime = this.ctx.currentTime;
this.lastChunkOffset = 0;
for (let i = 0;i<this.chunks.length;i++) {
let chunk = this.chunks[i];
chunk.start(this.startTime + this.lastChunkOffset);
this.lastChunkOffset += chunk.buffer.duration;
}
}
}
}
答案 2 :(得分:0)
我认为这是因为您为2个频道分配了缓冲区。 将其改为一个。
<DataTable value={this.state.sales.map(sale => sale.stdCtExamMarks)}>
到
context.createBuffer(2, data.length, sample_rate);