index.js
2.28 KB
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
'use strict'
const assert = require('assert')
const debug = require('debug')('record')
const { spawn } = require('child_process')
const recorders = require('./recorders')
class Recording {
constructor (options = {}) {
const defaults = {
sampleRate: 16000,
channels: 1,
compress: false,
threshold: 0.5,
thresholdStart: null,
thresholdEnd: null,
silence: '1.0',
recorder: 'sox',
endOnSilence: false,
audioType: 'wav'
}
this.options = Object.assign(defaults, options)
const recorder = recorders.load(this.options.recorder)
const { cmd, args, spawnOptions = {} } = recorder(this.options)
this.cmd = cmd
this.args = args
this.cmdOptions = Object.assign({ encoding: 'binary', stdio: 'pipe' }, spawnOptions)
debug(`Started recording`)
debug(this.options)
debug(` ${this.cmd} ${this.args.join(' ')}`)
return this.start()
}
start () {
const { cmd, args, cmdOptions } = this
const cp = spawn(cmd, args, cmdOptions)
const rec = cp.stdout
const err = cp.stderr
this.process = cp // expose child process
this._stream = rec // expose output stream
cp.on('close', code => {
if (code === 0) return
rec.emit('error', `${this.cmd} has exited with error code ${code}.
Enable debugging with the environment variable DEBUG=record.`
)
})
err.on('data', chunk => {
debug(`STDERR: ${chunk}`)
})
rec.on('data', chunk => {
debug(`Recording ${chunk.length} bytes`)
})
rec.on('end', () => {
debug('Recording ended')
})
return this
}
stop () {
assert(this.process, 'Recording not yet started')
this.process.kill()
}
pause () {
assert(this.process, 'Recording not yet started')
this.process.kill('SIGSTOP')
this._stream.pause()
debug('Paused recording')
}
resume () {
assert(this.process, 'Recording not yet started')
this.process.kill('SIGCONT')
this._stream.resume()
debug('Resumed recording')
}
isPaused () {
assert(this.process, 'Recording not yet started')
return this._stream.isPaused()
}
stream () {
assert(this._stream, 'Recording not yet started')
return this._stream
}
}
module.exports = {
record: (...args) => new Recording(...args)
}