Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use AudioWorklet to record microphone input #174

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions app/recorder.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class RecorderWorkletProcessor extends AudioWorkletProcessor {
process(inputs, outputs, parameters) {
if (this._number === undefined) {
this._number = 1
}

const timestamp = Date.now()
const buffer = new Uint8Array(inputs[0][0].buffer)
this.port.postMessage({ eventType: 'data', audioBuffer: buffer, timestamp: timestamp, number: this._number })
this._number++

return true
}
}

registerProcessor('recorder-worklet', RecorderWorkletProcessor)
63 changes: 59 additions & 4 deletions app/voice.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import keyboardjs from 'keyboardjs'
import vad from 'voice-activity-detection'
import DropStream from 'drop-stream'
import { WorkerBasedMumbleClient } from './worker-client'
import workletUrl from './recorder.js'

class VoiceHandler extends Writable {
constructor (client, settings) {
Expand Down Expand Up @@ -163,14 +164,68 @@ export class VADVoiceHandler extends VoiceHandler {
}

var theUserMedia = null
var oldBufferNumber = 0;

export function initVoice (onData) {
return window.navigator.mediaDevices.getUserMedia({ audio: true }).then((userMedia) => {
theUserMedia = userMedia
var micStream = new MicrophoneStream(userMedia, { objectMode: true, bufferSize: 1024 })
micStream.on('data', data => {
onData(Buffer.from(data.getChannelData(0).buffer))
})
setTimeout(() => audioContext().audioWorklet.addModule(workletUrl).then(() => {
console.log("AudioWorklet loaded!")
const recorderNode = new window.AudioWorkletNode(
audioContext(),
'recorder-worklet'
)
const microphone = audioContext().createMediaStreamSource(userMedia)
microphone.connect(recorderNode)

const delay_buffer = []
const delay_upperlimit = 30
recorderNode.port.onmessage = e => {
if (e.data.eventType === 'data') {
// Determine the delay between audio packet delivery (recorder.postMessage) and reception and
// stop forwarding audio packets to the voice pipeline, when the average delay is higher than
// delay_upperlimit.
// This prevents possible audio glitches induced by too high delays.
const timestamp = e.data.timestamp
const delay = Date.now() - timestamp
const newBufferNumber = e.data.number
var avg = 0

delay_buffer.push(delay)
if (delay_buffer.length < 10) {
console.debug("Not enough values!")
oldBufferNumber = newBufferNumber
return
}
if (delay_buffer.length > 10) {
delay_buffer.shift()
}
for (var i = 0; i < delay_buffer.length; i++) {
avg += delay_buffer[i]
}
avg /= delay_buffer.length
if (avg >= delay_upperlimit) {
console.log("Average delay too high! " + avg)
oldBufferNumber = newBufferNumber
return
}

// Only forward audio packets with higher buffer number (=new audio packets)
// to the voice pipe line
if (oldBufferNumber >= newBufferNumber) {
console.error("Old buffer occured!", oldBufferNumber, newBufferNumber)
} else {
if (oldBufferNumber + 1 != newBufferNumber) {
console.log("Buffer numbers don't fit!", oldBufferNumber, newBufferNumber)
}
oldBufferNumber = newBufferNumber
const audioData = e.data.audioBuffer
onData(audioData)
}
}
}
console.log("AudioWorkletNode initialized!")
}), 500)
return userMedia
})
}
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@
"web-audio-buffer-queue": "^1.1.0",
"webpack": "^4.44.2",
"webpack-cli": "^3.3.12",
"worker-loader": "^2.0.0"
"worker-loader": "^2.0.0",
"worklet-loader": "^1.0.0"
},
"optionalDependencies": {}
}
5 changes: 5 additions & 0 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ module.exports = {
test: /worker\.js$/,
use: { loader: 'worker-loader' }
},
{
test: /recorder\.js$/,
loader: 'worklet-loader',
options: {name:'[hash].audioworklet.js'}
},
{
enforce: 'post',
test: /mumble-streams\/lib\/data.js/,
Expand Down