TheBetterJORT
TheBetterJORT

Reputation: 808

Convert wav to mp3 using Meteor FS Collections on Startup

I'm trying to transcode all wav files into a mp3 using Meteor and Meteor FS Collections. My code works when I upload a wav file to the uploader -- That is it will convert the wav to a mp3 and allow me to play the file. But, I'm looking for a Meteor Solution that will transcode and add the file to the DB if the file is a wav and exist in a certain directory. According to the Meteor FSCollection it should be possible if the files have already been stored. Here is their example code: *GM is for ImageMagik, I've replaced gm with ffmpeg and installed ffmpeg from atmosphereJS.

Images.find().forEach(function (fileObj) {
  var readStream = fileObj.createReadStream('images');
  var writeStream = fileObj.createWriteStream('images');
  gm(readStream).swirl(180).stream().pipe(writeStream);
});

I'm using Meteor-CollectionFS [https://github.com/CollectionFS/Meteor-CollectionFS]-

if (Meteor.isServer) {
  Meteor.startup(function () {
        Wavs.find().forEach(function (fileObj) {
      var readStream = fileObj.createReadStream('.wavs/mp3');
      var writeStream = fileObj.createWriteStream('.wavs/mp3');
      this.ffmpeg(readStream).audioCodec('libmp3lame').format('mp3').pipe(writeStream);
      Wavs.insert(fileObj, function(err) {
      console.log(err);
    });
      });
      });
}

And here is my FS.Collection and FS.Store information. Currently everything resides in one JS file.

Wavs = new FS.Collection("wavs", {
  stores: [new FS.Store.FileSystem("wav"),
    new FS.Store.FileSystem("mp3",

    {
      path: '~/wavs/mp3',
      beforeWrite: function(fileObj) {
        return {
          extension: 'mp3',
          fileType: 'audio/mp3'
        };
      },
      transformWrite: function(fileObj, readStream, writeStream) {
        ffmpeg(readStream).audioCodec('libmp3lame').format('mp3').pipe(writeStream);
      }
    })]
});

When I try and insert the file into the db on the server side I get this error: MongoError: E11000 duplicate key error index:

Otherwise, If I drop a wav file into the directory and restart the server, nothing happens. I'm new to meteor, please help. Thank you.

Upvotes: 0

Views: 437

Answers (1)

ziomyslaw
ziomyslaw

Reputation: 211

Error is clear. You're trying to insert a next object with this same (duplicated) id, here you should first 'erase' the id or just update the document instead of adding the new one. If you not provide the _id field, it will be automatically added.

delete fileObj._id;
Wavs.insert(fileObj, function(error, result) {
}); 

See this How do I remove a property from a JavaScript object?

Why do you want to convert the files only on startup, I mean only one time? Probably you want to do this continuously, if yes then you should use this:

Tracker.autorun(function(){
    //logic
});

Upvotes: 1

Related Questions