Save AKSequencer output to local file

2019-05-18 17:58发布

问题:

I'm having issues while saving a midi using a sequencer to a local file. The audio is being created and saved, but the audio output is completely different as it should be.

Here is the code I'm using:

var sequencer : AKSequencer?
let piano = AKMIDISampler()
var offlineRender = AKOfflineRenderNode()

do {
   try piano.loadWav("mixloop")

   piano >>> offlineRender

   AudioKit.output = offlineRender
   sequencer = AKSequencer(filename: "melody")
   sequencer?.setGlobalMIDIOutput(piano.midiIn)

   AudioKit.start()

   let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
   let destAudioFile = docs.appendingPathComponent("rendered11.caf")

   offlineRender.internalRenderEnabled = false
   self.sequencer?.play()
   let seconds = sequencer?.length.seconds
   try self.offlineRender.renderToURL(destAudioFile, seconds: seconds ?? 4)
   self.sequencer!.stop()

   self.offlineRender.internalRenderEnabled = true
   print("Done! Rendered to " + destAudioFile.path)

   // test the local song using just AVAudioPlayer
   playLocalSong(url: destAudioFile)

} catch {
   print(error)
   return
}

I'm attaching the mixloop.wav, melody.mid and the output rendered11.caf. files

And if I change this line:

AudioKit.output = offlineRender

to

AudioKit.output = piano

The sound is just as it should be, with 16 seconds of sound instead of just the first few seconds.

Is something wrong in the code above?

Thanks in advance