I need to stop playing sound when the user leaves the passage, but there may be more tasks which should be executed when the passage is left, regardless of the way it was left (not only by clicking links, but all forms of goto as well). I think there should be some passage.OnExit() function? How should the code of the exit handler look?
I don't believe Sugarcane has a passage.OnExit() function but if you look at the passage render source code you will see that it does have the ability to supply a prerender (and postrender) handler which you may be able to use to do what you want (depending on exactly what you want to do) before the next passage is shown to the Reader.
The Prerender and postrender in Twine article may help you understand Sugarcane's prerender and postrender handlers.
Prerender and postrender are called when the passage is entered, not left!
I can think a workaround like starting setInterval(check(), 100), where check() will check if the current passage name have changed and run my own "onExit" for the previous passage, but this is a very ugly (and probably CPU-loading) solution. I hardly can believe there is no normal onExit handler.
In your case, a prerender task should work for stopping playback of your audio—since it would be called before the incoming passage is rendered, let alone displayed (the outgoing passage will still be onscreen at this point).
For example: As a specific example, showing how to use a Wikifer call to run macros:
If you really need to run a callback before anything is done for the incoming passage, then that is possible by wrapping the <History>.display() method. However, I suggest trying the prerender task first.
Actually, I came to conclusion that for some passage it is needed and for some it is not. So, they can be marked with "stopsound" tag, and the code will be