1

I have an existing app which uses worker concept to do audio download from an API. Now I would like to cut the audio once the download is complete in the same worker but the problem is before the full download completes trimming code runs in parellel which leads to empty file creation. Is there any way to wait for the worker to complete its download and do my splitting of audio? I am a complete beginner to node so any help would be appreciated.I am not very familiar with the promise and worker concepts. I am exploring it. Thanks in advance!

// connect to api
async function connectAPI() {
  await forLogin();
}

// after fetching data creating workers
async function startWorkers() {
  return new Promise((resolve, reject) => {
    // create array for storing data

    threads.add(new Worker("worker.js", { workerData: { worker: id, data: dataperWorker[id] } }));

    for (let worker of threads) {
      worker.on("error", () => {
        //handle error
      });

      worker.on("exit", () => {
        threads.delete(worker);

        return resolve;
      });
      worker.on("message", (message) => {
        //receive messages from worker
        switch (message.type) {
          case "log":
            break;
        }
      });
    }
  });
}
// worker.js

async function downloadAudio(workerId, data, storagePath) {
  await forGetRecordings();

  const file = fs.createWriteStream(`${storagePath}/fileName.mp3`);
  https.get(recordingsURL, async (response) => {
    response.pipe(file);
  });
}

// this is the one I have added to the existing app

function splitAudio(data, storagePath) {
  return new Promise((resolve, reject) => {
    for (const value of data.values) {
      // added some conditions on what basis to split

      ffmpeg(`${storagePath}/fileName.mp3`)
        .inputOptions([`-ss 40`, `-to 150`])

        .output(`${storagePath}/fileName_id.mp3`)
        .on("end", function () {
          logger.info(`Trimming records completed!`);
          return resolve();
        })

        .on("error", function (err) {
          logger.error(`Error occured ${err.message}`);
          return reject();
        })
        .run();
    }
  });
}

async function init(workerId, data) {
  //connect to api
  await forLogin();
  //create folders in local to download audio
  for (const i = 0; i < data.length; i++) {
    await downloadAudio(workerId, data[i], storagePath); // download full audio
    await splitAudio(data[i], storagePath); // I have added a function here
  }
}

init(workerData.worker, workerData.data);
dragon89
  • 11
  • 2
  • I think you need to return a promise from `downloadAudio` and await that. When `https#get` calls your callback function, resolve the promise. – prohit Dec 27 '22 at 13:59

0 Answers0