Prevent audio from flowing through speakers

I need to prevent audio from flowing through the speakers, however I do want audio to flow through the headphones if they are plugged in.


Basically I need to turn off the speakers while my app is running.


I have searched high and low, but all I can find is how to prevent headphones from being used, which is the opposite of what I need.