-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.js
More file actions
183 lines (153 loc) · 4.7 KB
/
main.js
File metadata and controls
183 lines (153 loc) · 4.7 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
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
// Generates a WAV audio file that consists solely of a tick at each beat where
// the timestamp of each beat is given by a Spotify audio analysis file. See
// ./README.md for details.
//
import fsPromises from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const metronomeTickPath = path.join(__dirname, './metronome-tick.wav');
function assert(pred, msg) {
if (!pred) {
throw new Error('Assert failed: ' + msg);
}
}
// WAV file parser & serializer
//
function ensureString(buffer, value, index) {
const actual = buffer.toString('utf8', index, index + value.length);
assert(value === actual, 'Unexpected value: ' + JSON.stringify({
expected: value,
actual,
}));
return actual;
}
function ensureUInt16LE(buffer, value, index) {
const actual = buffer.readUInt16LE(index);
assert(value === actual, 'Unexpected value: ' + JSON.stringify({
expected: value,
actual,
}));
return actual;
}
function ensureUInt32LE(buffer, value, index) {
const actual = buffer.readUInt32LE(index);
assert(value === actual, 'Unexpected value: ' + JSON.stringify({
expected: value,
actual,
}));
return actual;
}
function parseWav(buffer) {
const chunkId = ensureString(buffer, 'RIFF', 0);
const chunkSize = buffer.readUInt32LE(4);
const format = ensureString(buffer, 'WAVE', 8);
const subchunk1Id = ensureString(buffer, 'fmt ', 12);
const subchunk1Size = ensureUInt32LE(buffer, 16, 16); // 16 for PCM
const audioFormat = ensureUInt16LE(buffer, 1, 20); // 1 for PCM
const numChannels = buffer.readUInt16LE(22);
const sampleRate = buffer.readUInt32LE(24);
const byteRate = buffer.readUInt32LE(28);
const blockAlign = buffer.readUInt16LE(32);
const bitsPerSample = buffer.readUInt16LE(34);
const subchunk2Id = ensureString(buffer, 'data', 36);
const subchunk2Size = buffer.readUInt32LE(40);
const data = buffer.slice(44);
return {
chunkId,
chunkSize,
format,
subchunk1Id,
subchunk1Size,
audioFormat,
numChannels,
sampleRate,
byteRate,
blockAlign,
bitsPerSample,
subchunk2Id,
subchunk2Size,
data,
};
}
function serializeWav({
numChannels,
sampleRate,
byteRate,
blockAlign,
bitsPerSample,
data,
}) {
const fileSize = 44 + data.length;
const buffer = new Buffer.alloc(fileSize);
buffer.write('RIFF', 0);
buffer.writeUInt32LE(fileSize - 8, 4);
buffer.write('WAVE', 8);
buffer.write('fmt ', 12);
buffer.writeUInt32LE(16, 16); // 16 for PCM
buffer.writeUInt16LE(1, 20); // 1 for PCM
buffer.writeUInt16LE(numChannels, 22);
buffer.writeUInt32LE(sampleRate, 24);
buffer.writeUInt32LE(byteRate, 28);
buffer.writeUInt16LE(blockAlign, 32);
buffer.writeUInt16LE(bitsPerSample, 34);
buffer.write('data', 36);
buffer.writeUInt32LE(data.length, 40);
data.copy(buffer, 44, 0);
return buffer;
}
// Utility for generating a WAV file that plays a sound at specific timestamps.
//
class WavTickBuilder {
constructor(wav, tick) {
this._wav = wav;
this._tick = tick;
this._pieces = [];
this._lengthBytes = 0;
this._bytesPerSample = this._wav.blockAlign;
this._samplesPerSecond = this._wav.sampleRate;
}
get _lengthSamples() {
return this._lengthBytes / this._bytesPerSample;
}
_makeSilence(lengthSamples) {
return Buffer.alloc(lengthSamples * this._bytesPerSample);
}
addTickAt(seconds) {
const sampleOffset = (seconds * this._samplesPerSecond) | 0;
const gapSamples = sampleOffset - this._lengthSamples;
assert(gapSamples >= 0, 'Cannot add a tick in the past');
const silence = this._makeSilence(gapSamples);
this._pieces.push(silence);
this._pieces.push(this._tick);
this._lengthBytes += silence.length + this._tick.length;
}
getWav() {
return serializeWav({
...this._wav,
data: Buffer.concat(this._pieces),
});
}
}
// main
//
async function main(args) {
if (args.length !== 2) {
console.log('Usage: node main.js <spotify-analysis.json> <beat-output.wav>');
return;
}
const [spotifyAnalysisPath, beatOutputPath] = args;
const content = await fsPromises.readFile(spotifyAnalysisPath, { encoding: 'utf8' });
const spotifyAnalysis = JSON.parse(content);
const beats = spotifyAnalysis.beats;
const tickBuffer = await fsPromises.readFile(metronomeTickPath);
const tickWav = parseWav(tickBuffer);
const builder = new WavTickBuilder(tickWav, tickWav.data);
for (const beat of beats) {
builder.addTickAt(beat.start);
}
await fsPromises.writeFile(beatOutputPath, builder.getWav());
console.log('Wrote ' + beats.length + ' beats to ' + beatOutputPath);
}
main(process.argv.slice(2));