在节点js中将wav转换为mp3

时间:2015-08-13 04:52:35

标签: sox aws-lambda

是否有任何npn包将wav文件转换为节点js中的mp3文件?我想在aws lambda函数中运行这个脚本。我试过sox和sox-audio包,但lambda不支持它。我google了ffmpeg,没有找到wav和mp3之间的任何转换。

是否有人在节点js中提供了良好的转换包?

console.log('New Lambda Call');

var async = require('async');
var aws = require('aws-sdk');
var fs = require('fs');
var uuid = require('node-uuid');
var SoxCommand = require('sox-audio');
var sox = require('sox');

var s3 = new aws.S3({ apiVersion: '2006-03-01' });

exports.handler = function(event, context) {

    //console.log('Reading event option : ', JSON.stringify(event, null, 2));

    var src_bucket = event.Records[0].s3.bucket.name;
    var key = event.Records[0].s3.object.key;
    var src_key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " "));
    var dest_bucket = "dmlambda";
    var desk_key = src_key;

    var params = {
        Bucket: src_bucket,
        Key: src_key
    };

    if (src_bucket == dest_bucket) {
        console.error("Destination bucket must not match source bucket.");
        return;
    }

    var typeMatch = src_key.match(/\.([^.]*)$/);
    if (!typeMatch) {
        console.error('unable to infer audio type for key ' + src_key);
        return;
    }

    console.log()

    var audioType = typeMatch[1];
    if (audioType != "wav") {
        console.log('skipping non wav audio ' + src_key);
        return;
    }

    s3.getObject(params, function(err, data){

        if (err) {

            console.log(err);

            var message = "Error getting object " + src_key + " from bucket " + src_bucket +
                ". Make sure they exist and your bucket is in the same region as this function.";
            console.log(message);

        } else {

            console.log('Audio Content type:', data.ContentType);

            fs.writeFile('./tmp/temp_'+src_key, data.Body, {encoding: null}, function(err){

                if(err){

                    console.log("download file write error"+ err);

                } else {

                    console.log('Added temp_'+src_key+' to queue');

                    var arr = src_key.split(".");
                    var filename = arr[0];

                    var command = SoxCommand()
                            .input('./tmp/temp_'+src_key)
                            .output('./tmp/'+filename+'.mp3')
                            .outputFileType('mp3')
                            .outputSampleRate(44100)
                            .outputBits(192 * 1024)
                            .outputChannels(2);

                    command.on('prepare', function(args) {

                        console.log('Preparing sox command with args ' + args.join(' '));

                    });

                    command.on('start', function(commandLine) {

                        console.log('Spawned sox with command ' + commandLine);

                    });

                    command.on('progress', function(progress) {

                        console.log('Processing progress: ', progress);

                    });

                    command.on('error', function(err, stdout, stderr) {

                        console.log('Cannot process audio: ' + err.message);
                        console.log('Sox Command Stdout: ', stdout);
                        console.log('Sox Command Stderr: ', stderr);

                    });

                    command.on('end', function() {

                        fs.unlink('./tmp/temp_'+src_key, function(err){

                            if(err){

                                console.log("delete error : ",err);

                            } else {

                                console.log('Moved temp_'+src_key);

                            }

                        });

                        console.log('Sox command succeeded!');

                        var stream = fs.createReadStream('./tmp/'+filename+'.mp3');

                        s3.putObject({
                            Bucket: dest_bucket,
                            Key: filename+'.mp3',
                            Body: stream
                          }, function(err, data){
                             if(err){

                                console.log("upload error : ",err);

                             } else {

                                fs.unlink('./tmp/'+filename+'.mp3', function(err){

                                    if(err){

                                        console.log("delete error : ",err);

                                    } else {

                                        console.log('Moved '+filename+'.mp3');

                                    }

                                 });

                            }

                         });

                    });

                    command.run();

                }  

            });

        }

    });

};

Lambda日志是:

2015-08-13T05:39:21.845Z    vg7ewk1gk1bjvn30    New Lambda Call

START RequestId: a5ec9286-417d-11e5-9a79-310ba41a5a40

2015-08-13T05:39:21.990Z    a5ec9286-417d-11e5-9a79-310ba41a5a40    

2015-08-13T05:39:22.285Z    a5ec9286-417d-11e5-9a79-310ba41a5a40    Audio Content type: audio/x-wav

2015-08-13T05:39:22.320Z    a5ec9286-417d-11e5-9a79-310ba41a5a40    Added temp_RE4bc9f41b1738c6def250a58e32d473aa.wav to queue

2015-08-13T05:39:22.322Z    a5ec9286-417d-11e5-9a79-310ba41a5a40    Preparing sox command with args ./tmp/temp_RE4bc9f41b1738c6def250a58e32d473aa.wav -t mp3 -r 44100 -b 196608 -c 2 ./tmp/RE4bc9f41b1738c6def250a58e32d473aa.mp3

2015-08-13T05:39:22.366Z    a5ec9286-417d-11e5-9a79-310ba41a5a40    Cannot process audio: Cannot find sox

2015-08-13T05:39:22.366Z    a5ec9286-417d-11e5-9a79-310ba41a5a40    Sox Command Stdout: null

2015-08-13T05:39:22.366Z    a5ec9286-417d-11e5-9a79-310ba41a5a40    Sox Command Stderr: 

END RequestId: a5ec9286-417d-11e5-9a79-310ba41a5a40
Process exited before completing request

2 个答案:

答案 0 :(得分:4)

sox npm package只是 sox CLI的界面。

在错误日志中,它显示Cannot process audio: Cannot find sox。这是因为您没有安装实际的sox CLI。安装它。

为了在the AWS blog中包含sox CLI,来自here

  

包含您自己的可执行文件很容易;只需将它们打包到您上传的ZIP文件中,然后在从Node.js或之前启动的其他进程中调用它们时引用它们(包括您创建的ZIP文件中的相对路径)。确保在功能代码的开头包含以下内容:

     

process.env ['PATH'] = process.env ['PATH'] +':'+ process.env ['LAMBDA_TASK_ROOT']

总结一下,您想要:

  1. 下载sox CLI {{3}},
  2. 将其包含在您上传的zip中
  3. 在节点文件的顶部添加特殊process.env ...行,并
  4. 运行

答案 1 :(得分:1)

因为您已经在使用AWS。为什么不使用elastic transcoder代替Lambda。弹性转码器专门用于转码音频/视频文件。

您甚至可以根据放入s3存储桶的文件来触发它。