sinshu / meltysynth

A SoundFont MIDI synthesizer for .NET
Other
130 stars 15 forks source link

Generate specific sample range and change position #38

Closed achimmihca closed 1 year ago

achimmihca commented 1 year ago

I have a Unity game and want to play user provided MIDI files on the fly.

Therefor, I want to synthesize samples when needed, not all at once. For example, my code may look similar to this:

private void CreateAudioClip()
{
    audioSource.clip = AudioClip.Create("MIDI {fileName}", audioClipLengthInSamples, midiSynthesizerChannelCount, audioClipSampleRate, true, OnAudioClipRead, OnAudioClipSetPosition);
}

private void OnAudioClipRead(float[] data)
{
    // This method is called when Unity plays the audio.
    // It asks for samples from `audioClip.timeSamples` to `audioClip.timeSamples + data.Length`
    FillOutputBuffer(data, midiSynthesizerChannelCount);
}

private void OnAudioClipSetPosition(int positionInSamples)
{
    // This method is called when Unity changes the playback position.
    // It sets audioClip.timeSamples
    sequencer.SeekSampleTime(positionInSamples);
}

I found the Render method of MeltySynth to be good. However, I did not find a way to change the playback position. Is this missing or am I looking in the wrong place?

So far, I use this other lib to play MIDI in Unity, but it has issues with some MIDI files.

Thanks for the help!

sinshu commented 1 year ago

MIDI files inherently do not work well with operations like seeking, and it's challenging to implement a seek function that can meet the demands of many users. Therefore, the MidiFileSequencer in MeltySynth does not provide a seek method. If you need to seek, please consider implementing your own sequencer.

achimmihca commented 1 year ago

Thanks for the info. In this case, I will close this issue.