-
Notifications
You must be signed in to change notification settings - Fork 1
/
processor.ts
101 lines (86 loc) · 2.42 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
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
import * as fs from 'fs';
import {Riff, Fmt, iXML} from './riff';
class Processor {
constructor() {}
/**
* add iXML chunk to wav buffer.
*/
encode(wavBuffer: Buffer, trackName: string): Promise<Buffer> {
return new Promise((resolve, reject) => {
// parse wav file
let riff = Riff.from(wavBuffer);
// already has iXML chunk ?
for (let chunk of riff.subChunks) {
if (chunk instanceof iXML) {
return resolve(null);
}
}
// get numChannels
let numChannels = 1;
for (let chunk of riff.subChunks) {
if (chunk instanceof Fmt) {
numChannels = chunk.numChannels;
}
}
// add iXML chunk
let iXMLChunk = iXML.fromTrackName(trackName, numChannels);
riff.appendChunk(iXMLChunk);
// write file
let wbuffer = Buffer.alloc(riff.chunkLength);
riff.write(wbuffer);
return resolve(wbuffer);
});
}
encodeSync(wavBuffer: Buffer, trackName: string): Buffer {
// parse wav file
let riff = Riff.from(wavBuffer);
// already has iXML chunk ?
for (let chunk of riff.subChunks) {
if (chunk instanceof iXML) {
return null;
}
}
// get numChannels
let numChannels = 1;
for (let chunk of riff.subChunks) {
if (chunk instanceof Fmt) {
numChannels = chunk.numChannels;
}
}
// add iXML chunk
let iXMLChunk = iXML.fromTrackName(trackName, numChannels);
riff.appendChunk(iXMLChunk);
// write file
let wbuffer = Buffer.alloc(riff.chunkLength);
riff.write(wbuffer);
return wbuffer;
}
/**
* append iXML chunk to wav file.
*/
append(filePath: string, trackName: string, outPath: string): Promise<string> {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'binary', (err, content) => {
if (err) {
return reject(err);
}
// parse wav file
let buffer = Buffer.from(content, 'binary');
// append ixml chunk
this.encode(buffer, trackName).then((wbuffer: Buffer) => {
if (!wbuffer) {
return resolve(null);
}
// write file
fs.writeFile(outPath, wbuffer, 'binary', (err) => {
if (err) {
return reject(err);
}
return resolve(outPath);
});
}); // encode
}); // fs.readFile
}); // Promise
}
}
export default Processor;