schellingb / TinySoundFont

SoundFont2 synthesizer library in a single C/C++ file
MIT License
608 stars 71 forks source link

How I can stop a note by fading the volume? #56

Closed dortamiguel closed 3 years ago

dortamiguel commented 3 years ago

So when I turn off a note the sound stops completely, this is very abrupt and I will like it to stop it smoothly.

Is this possible?

I was thinking I could turn off the volume gradually until it reaches zero, is there something already built in for this on the library?

I tried to change the volume of a note by calling tsf_note_on with a lower velocity but it resets the note to the beginning.

Is it possible to have different notes with different volumes and fade them away after some time?

schellingb commented 3 years ago

If the soundfont is designed with instruments that have a release envelope that fades out over time, TSF should use that when calling any one of tsf_note_off, tsf_bank_note_off,tsf_note_off_all,tsf_channel_note_offortsf_channel_note_off_all`.

I guess if you want to override that default behavior I don't think there's a nice built in way to do that.

If you're playing notes with the tsf_channel_ MIDI style interface there is tsf_channel_set_volume to set the volume of all voices currently playing that were started on a given channel.

But to do it to the default tsf_note_on you'd probably need to modify the library. For example you probably could copy the tsf_note_off to a new tsf_note_off_slow that takes a float release_time argument which then would do something like

...
v->ampenv.parameters.release = release_time; // time in seconds
v->modenv.parameters.release = release_time; // time in seconds
tsf_voice_end(f, v);
...

(note untested)

Or maybe you could pass an (optional) callback function to tsf_note_on like void (*voice_callback)(struct tsf_voice *voice) and then call if (voice_callback) voice_callback(voice); at the end of the "// Play all matching regions" for-loop. Then in your passed voice callback you could set the parameters.release values like in the example above. (also untested).

dortamiguel commented 3 years ago

Ah! You are right, it was the font I was using. With the default piano preset the audio fades. Thank you 🙂