This repository has been archived by the owner on May 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocessor.ts
60 lines (54 loc) · 1.76 KB
/
processor.ts
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
import { startRecord, stopRecord } from './mic'
let context: AudioContext | undefined
let source: MediaStreamAudioSourceNode | undefined
let processor: ScriptProcessorNode | undefined
export interface ProcessorReturnValue {
context: AudioContext
processor: ScriptProcessorNode
}
/**
* Underlying utility method for recording audio,
* used by the `record` and `recordStream` methods.
*
* While createScriptProcessor is deprecated, the replacement (AudioWorklet)
* does not yet have broad support (currently only supported in Blink browsers).
* See https://caniuse.com/#feat=mdn-api_audioworkletnode
*
* We'll switch to AudioWorklet when it does.
*/
export async function startProcessor(): Promise<[Error] | [null, ProcessorReturnValue]> {
stopProcessor()
let stream: MediaStream
try {
stream = await startRecord()
} catch (e) {
console.error(e)
return [
new Error(
`There was a problem starting the microphone. ${
navigator.__polyfilledMediaDevices
? 'This browser does not support microphone access.'
: 'Please check the permission and try again.'
}`
)
]
}
const context = new (window.AudioContext || window.webkitAudioContext)()
const source = context.createMediaStreamSource(stream)
const processor = context.createScriptProcessor(1024, 1, 1)
source.connect(processor)
processor.connect(context.destination)
return [null, { context, processor }]
}
/**
* Underlying utility method to stop the current processor
* if it exists and disconnect the microphone.
*/
export function stopProcessor() {
stopRecord()
if (context && source && processor) {
source.disconnect(processor)
processor.disconnect(context.destination)
}
context = source = processor = undefined
}