How to prevent MacOS from sleeping when sound is playing

One possible solution is the application Amphetamine. This app's sole purpose is to prevent the computer from going to sleep when you don't want it too. One of the things it is capable of is conditional sleep prevention. To set this up install the app then in the apps preferences page go the "Triggers" add a new trigger using the "+" button. Name the trigger. Then add the criterion "audio output" using the "+". Then find the HDMI audio output in the drop down box and you're done. (Note: The HDMI audio output might not show up if you are not connected to your TV) Hope this Helps.

Edit: To increase the granularity of the control, you can add multiple condition in the trigger so that all conditions must be met for it to enable. The application trigger will limit it to only if the web browser is open (with a toggle to specify if it needs to be frontmost)(As this isn't perfect you can use another browser to play the music other than your standard browser to avoid unwanted activation) and if you still want even more granularity you can use CPU utilization as a sort of proxy of the app playing audio. (though this will be inconsistent and would only work if the web browser uses a relatively significant amount of resources while playing music to distinguish it from background activity). Hope these possible workarounds help.