如何在JavaScript中制作声音文件?

时间:2014-10-30 17:42:44

标签: javascript audio buffer

我想制作一个生成wav格式声音文件的代码。然而,我试图玩它时卡住了。这就是我到目前为止所做的:

var fs = require("fs");
var buf = new Buffer(176400);
var fileName = "i_write_this_wave.wav";
var fd = fs.openSync(fileName, "w");
buf.writeUInt32BE(0x52494646, 0);
buf.writeUInt32LE(0x24080000, 4);
buf.writeUInt32BE(0x57415645, 8);
buf.writeUInt32BE(0x666d7420, 12);
buf.writeUInt32LE(0x10000000, 16);
buf.writeUInt16LE(0x0100, 20);
buf.writeUInt16LE(0x0200, 22);
buf.writeUInt32LE(0x22560000, 24);
buf.writeUInt32LE(0x88580100, 28);
buf.writeUInt16LE(0x0400, 32);
buf.writeUInt16LE(0x1000, 34);
buf.writeUInt32BE(0x64617461, 36);
buf.writeUInt32LE(0x00080000, 40);
var vl = 32000;
var of = 44;
while (of < 176400) {
buf.writeUInt16LE(vl, of);
of = of + 2;
}
fs.writeSync(fd, buf, 0, buf.length);

它使wav文件具有正确的标题等,但我无法播放它。我认为缓冲区大小有问题,但缓冲区的大小应该是多少?如果您有任何建议,请与他们联系。

1 个答案:

答案 0 :(得分:0)

您滥用writeUInt16LEwriteUInt32LE。例如,如果要以小端编写32位整数0x5622,则应使用

buf.writeUInt32LE(0x5622, 24);

您正在反转以little endian编写的每个值,导致那些以big endian出现在文件中,这将导致文件无效。

具体而言,以下是我重写代码的方法:

var fs = require("fs");
var buf = new Buffer(176400);
var fileName = "i_write_this_wave.wav";
var fd = fs.openSync(fileName, "w");
buf.writeUInt32BE(0x52494646, 0);
buf.writeUInt32LE(buf.length-8, 4);
buf.writeUInt32BE(0x57415645, 8);
buf.writeUInt32BE(0x666d7420, 12);
buf.writeUInt32LE(0x10, 16);
buf.writeUInt16LE(0x01, 20);
buf.writeUInt16LE(0x02, 22);
buf.writeUInt32LE(0x5622, 24);
buf.writeUInt32LE(0x15888, 28);
buf.writeUInt16LE(0x04, 32);
buf.writeUInt16LE(0x10, 34);
buf.writeUInt32BE(0x64617461, 36);
buf.writeUInt32LE(buf.length-44, 40);
var vl = 32000;
var of = 44;
while (of < 176400) {
    buf.writeUInt16LE(vl, of);
    of = of + 2;
}
fs.writeSync(fd, buf, 0, buf.length);