timidity icon indicating copy to clipboard operation
timidity copied to clipboard

Add render() method to get raw sample data.

Open chr15m opened this issue 4 years ago • 0 comments

Hi @feross, thanks for this wonderful library which I'm using over at https://dopeloop.ai/melody-generator. For a different application I wanted to be able to get the raw audio samples of the rendered MIDI file, and this patch adds that functionality with the render() method. It returns a pair of Float32Arrays containing the left and right channel audio data, which can then be used to mix with other audio, compress to mp3, or whatever. I also updated the documentation. I know you are super busy, so thank you for considering this PR for merging. :pray:

Here is some test code for trying out the render() method:

const Timidity = require('timidity')

const player = new Timidity()

player.load('/pachelbel_canon.mid')

player.on("progress", function(value, total) {
  console.log("progress", value, "/", total)
});

player.on("loaded", function() {
  console.log("duration:", player.duration)
  console.log("song:", player._currentUrlOrBuf)
  const arrays = player.render()
  console.log(arrays)

  var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
  var myArrayBuffer = audioCtx.createBuffer(2, arrays[0].length, audioCtx.sampleRate);
  for (var channel = 0; channel < myArrayBuffer.numberOfChannels; channel++) {
    myArrayBuffer.copyToChannel(arrays[channel], channel)
  }
  var source = audioCtx.createBufferSource();
  source.buffer = myArrayBuffer;
  source.connect(audioCtx.destination);
  source.start();
})

chr15m avatar May 17 '21 04:05 chr15m