forked from tonistiigi/audiosprite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
audiosprite.js
executable file
·324 lines (291 loc) · 8.86 KB
/
audiosprite.js
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
var fs = require('fs')
var path = require('path')
var async = require('async')
var _ = require('underscore')._
var defaults = {
output: 'output',
path: '',
export: 'ogg,m4a,mp3,ac3',
format: null,
autoplay: null,
loop: [],
silence: 0,
gap: 1,
minlength: 0,
bitrate: 128,
vbr: -1,
samplerate: 44100,
channels: 1,
rawparts: '',
logger: {
debug: function(){},
info: function(){},
log: function(){}
}
}
module.exports = function(files) {
var opts = {}, callback = function(){}
if (arguments.length == 2) {
callback = arguments[1]
} else if (arguments.length >= 3) {
opts = arguments[1]
callback = arguments[2]
}
if (!files || !files.length) return callback(new Error('No input files specified.'))
opts = _.extend({}, defaults, opts)
// make sure output directory exists
var outputDir = path.dirname(opts.output)
if (!fs.existsSync(outputDir)) {
require('mkdirp').sync(outputDir)
}
var offsetCursor = 0
var wavArgs = ['-ar', opts.samplerate, '-ac', opts.channels, '-f', 's16le']
var tempFile = mktemp('audiosprite')
opts.logger.debug('Created temporary file', { file: tempFile })
var json = {
resources: []
, spritemap: {}
}
spawn('ffmpeg', ['-version']).on('exit', function(code) {
if (code) {
callback(new Error('ffmpeg was not found on your path'))
}
if (opts.silence) {
json.spritemap.silence = {
start: 0
, end: opts.silence
, loop: true
}
if (!opts.autoplay) {
json.autoplay = 'silence'
}
appendSilence(opts.silence + opts.gap, tempFile, processFiles)
} else {
processFiles()
}
})
function mktemp(prefix) {
var tmpdir = require('os').tmpDir() || '.'
return path.join(tmpdir, prefix + '.' + Math.random().toString().substr(2))
}
function spawn(name, opt) {
opts.logger.debug('Spawn', { cmd: [name].concat(opt).join(' ') })
return require('child_process').spawn(name, opt)
}
function pad(num, size) {
var str = num.toString()
while (str.length < size) {
str = '0' + str
}
return str
}
function makeRawAudioFile(src, cb) {
var dest = mktemp('audiosprite')
opts.logger.debug('Start processing', { file: src})
fs.exists(src, function(exists) {
if (exists) {
var ffmpeg = spawn('ffmpeg', ['-i', path.resolve(src)]
.concat(wavArgs).concat('pipe:'))
ffmpeg.stdout.pipe(fs.createWriteStream(dest, {flags: 'w'}))
ffmpeg.on('exit', function(code, signal) {
if (code) {
return cb({
msg: 'File could not be added',
file: src,
retcode: code,
signal: signal
})
}
cb(null, dest)
})
}
else {
cb({ msg: 'File does not exist', file: src })
}
})
}
function appendFile(name, src, dest, cb) {
var size = 0
var reader = fs.createReadStream(src)
var writer = fs.createWriteStream(dest, {
flags: 'a'
})
reader.on('data', function(data) {
size += data.length
})
reader.on('close', function() {
var originalDuration = size / opts.samplerate / opts.channels / 2
opts.logger.info('File added OK', { file: src, duration: originalDuration })
var extraDuration = Math.max(0, opts.minlength - originalDuration)
var duration = originalDuration + extraDuration
json.spritemap[name] = {
start: offsetCursor
, end: offsetCursor + duration
, loop: name === opts.autoplay || opts.loop.indexOf(name) !== -1
}
offsetCursor += originalDuration
appendSilence(extraDuration + Math.ceil(duration) - duration + opts.gap, dest, cb)
})
reader.pipe(writer)
}
function appendSilence(duration, dest, cb) {
var buffer = new Buffer(Math.round(opts.samplerate * 2 * opts.channels * duration))
buffer.fill(0)
var writeStream = fs.createWriteStream(dest, { flags: 'a' })
writeStream.end(buffer)
writeStream.on('close', function() {
opts.logger.info('Silence gap added', { duration: duration })
offsetCursor += duration
cb()
})
}
function exportFile(src, dest, ext, opt, store, cb) {
var outfile = dest + '.' + ext
spawn('ffmpeg',['-y', '-ar', opts.samplerate, '-ac', opts.channels, '-f', 's16le', '-i', src]
.concat(opt).concat(outfile))
.on('exit', function(code, signal) {
if (code) {
return cb({
msg: 'Error exporting file',
format: ext,
retcode: code,
signal: signal
})
}
if (ext === 'aiff') {
exportFileCaf(outfile, dest + '.caf', function(err) {
if (!err && store) {
json.resources.push(dest + '.caf')
}
fs.unlinkSync(outfile)
cb()
})
} else {
opts.logger.info('Exported ' + ext + ' OK', { file: outfile })
if (store) {
json.resources.push(outfile)
}
cb()
}
})
}
function exportFileCaf(src, dest, cb) {
if (process.platform !== 'darwin') {
return cb(true)
}
spawn('afconvert', ['-f', 'caff', '-d', 'ima4', src, dest])
.on('exit', function(code, signal) {
if (code) {
return cb({
msg: 'Error exporting file',
format: 'caf',
retcode: code,
signal: signal
})
}
opts.logger.info('Exported caf OK', { file: dest })
return cb()
})
}
function processFiles() {
var formats = {
aiff: []
, wav: []
, ac3: ['-acodec', 'ac3', '-ab', opts.bitrate + 'k']
, mp3: ['-ar', opts.samplerate, '-f', 'mp3']
, mp4: ['-ab', opts.bitrate + 'k']
, m4a: ['-ab', opts.bitrate + 'k']
, ogg: ['-acodec', 'libvorbis', '-f', 'ogg', '-ab', opts.bitrate + 'k']
}
if (opts.vbr >= 0 && opts.vbr <= 9) {
formats.mp3 = formats.mp3.concat(['-aq', opts.vbr])
}
else {
formats.mp3 = formats.mp3.concat(['-ab', opts.bitrate + 'k'])
}
if (opts.export.length) {
formats = opts.export.split(',').reduce(function(memo, val) {
if (formats[val]) {
memo[val] = formats[val]
}
return memo
}, {})
}
var rawparts = opts.rawparts.length ? opts.rawparts.split(',') : null
var i = 0
async.forEachSeries(files, function(file, cb) {
i++
makeRawAudioFile(file, function(err, tmp) {
if (err) {
return cb(err)
}
function tempProcessed() {
fs.unlinkSync(tmp)
cb()
}
var name = path.basename(file).replace(/\.[a-zA-Z0-9]+$/, '')
appendFile(name, tmp, tempFile, function(err) {
if (rawparts != null ? rawparts.length : void 0) {
async.forEachSeries(rawparts, function(ext, cb) {
opts.logger.debug('Start export slice', { name: name, format: ext, i: i })
exportFile(tmp, opts.output + '_' + pad(i, 3), ext, formats[ext]
, false, cb)
}, tempProcessed)
} else {
tempProcessed()
}
})
})
}, function(err) {
if (err) {
return callback(new Error('Error adding file'))
}
async.forEachSeries(Object.keys(formats), function(ext, cb) {
opts.logger.debug('Start export', { format: ext })
exportFile(tempFile, opts.output, ext, formats[ext], true, cb)
}, function(err) {
if (err) {
return callback(new Error('Error exporting file'))
}
if (opts.autoplay) {
json.autoplay = opts.autoplay
}
json.resources = json.resources.map(function(e) {
return opts.path ? path.join(opts.path, path.basename(e)) : e
})
var finalJson = {}
switch (opts.format) {
case 'howler':
finalJson.urls = [].concat(json.resources)
finalJson.sprite = {}
for (var sn in json.spritemap) {
var spriteInfo = json.spritemap[sn]
finalJson.sprite[sn] = [spriteInfo.start * 1000, (spriteInfo.end - spriteInfo.start) * 1000]
if (spriteInfo.loop) {
finalJson.sprite[sn].push(true)
}
}
break
case 'createjs':
finalJson.src = json.resources[0]
finalJson.data = {audioSprite: []}
for (var sn in json.spritemap) {
var spriteInfo = json.spritemap[sn]
finalJson.data.audioSprite.push({
id: sn,
startTime: spriteInfo.start * 1000,
duration: (spriteInfo.end - spriteInfo.start) * 1000
})
}
break
case 'default': // legacy support
default:
finalJson = json
break
}
fs.unlinkSync(tempFile)
callback(null, finalJson)
})
})
}
}