-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaudioprocessor.js
136 lines (117 loc) · 4.85 KB
/
audioprocessor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** -------------------------------------------------------------------------*/
export class AudioProcessor {
decoder = null;
audioBufferQueue = { bufferQueue: new Set(), nextBufferTime: 0 };
onloadedcallback = null;
loaded = false;
constructor(audioContext, onloadedcallback) {
this.onloadedcallback = onloadedcallback;
this.audioContext = audioContext;
this.gain = this.audioContext.createGain();
this.gain.connect(this.audioContext.destination);
}
setVolume(volume) {
this.gain.gain.value = volume;
}
async onAudioFrame(metadata, data) {
if (!this.decoder || this.decoder.state === "closed") {
this.decoder = this._createAudioDecoder();
}
if (this.decoder.state !== "configured") {
const codec = metadata.codec;
const sampleRate = metadata.freq;
const numberOfChannels = metadata.channels;
const config = { codec, sampleRate, numberOfChannels };
const support = await AudioDecoder.isConfigSupported(config);
if (support.supported) {
console.log(`decoder supported with codec ${codec}`);
await this.decoder.configure(config);
} else {
return Promise.reject(`${codec} is not supported`);
}
}
if (this.decoder.state === "configured") {
const chunk = new EncodedAudioChunk({
timestamp: metadata.ts,
type: "key",
data,
});
await this.decoder.decode(chunk);
return Promise.resolve();
} else {
this._changeState(false);
return Promise.reject(`${metadata.codec} decoder not configured`);
}
}
close() {
this._changeState(false);
if (this.decoder && this.decoder.state !== "closed") {
this.decoder.close();
}
this._clearBufferQueue();
}
_clearBufferQueue() {
this.audioBufferQueue.bufferQueue.forEach(source => source.stop());
this.audioBufferQueue.bufferQueue.clear();
this.audioBufferQueue.nextBuffer = 0;
}
_changeState(state) {
if (this.loaded != state) {
this?.onloadedcallback(state);
this.loaded = state;
}
}
async _processAudioFrame(frame) {
this._changeState(true);
if (this.audioBufferQueue.bufferQueue.size > 100) {
console.log('audio buffer queue is full, clearing');
this._clearBufferQueue();
}
const { numberOfChannels, numberOfFrames, sampleRate, format } = frame;
const audioBuffer = this.audioContext.createBuffer(numberOfChannels, numberOfFrames, sampleRate);
if (format.endsWith('-planar')) {
for (let channel = 0; channel < numberOfChannels; channel++) {
const channelData = new Float32Array(numberOfFrames);
frame.copyTo(channelData, { planeIndex: channel });
audioBuffer.copyToChannel(channelData, channel);
}
} else {
const interleavingBuffer = new Float32Array(numberOfFrames*numberOfChannels);
frame.copyTo(interleavingBuffer, { planeIndex: 0 });
for (let channel = 0; channel < numberOfChannels; channel++) {
const channelData = new Float32Array(numberOfFrames);
for (let i = 0; i < numberOfFrames; i++) {
channelData[i] = interleavingBuffer[i * numberOfChannels + channel];
}
audioBuffer.copyToChannel(channelData, channel);
}
}
this._queueAudioBuffer(audioBuffer);
frame.close();
}
_queueAudioBuffer(audioBuffer) {
const source = this.audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(this.gain);
this.audioBufferQueue.bufferQueue.add(source);
if (this.audioContext.currentTime > this.audioBufferQueue.nextBufferTime) {
source.start();
this.audioBufferQueue.nextBufferTime = this.audioContext.currentTime + audioBuffer.duration;
} else {
source.start(this.audioBufferQueue.nextBufferTime);
this.audioBufferQueue.nextBufferTime += audioBuffer.duration;
}
source.onended = () => this.audioBufferQueue.bufferQueue.delete(source);
}
_createAudioDecoder() {
return new AudioDecoder({
output: (frame) => this._processAudioFrame(frame),
error: (e) => console.log(e.message),
});
}
}