How does the phone know to switch from playing music through speakers to playing music through the headphones

Solution
The sound flows thru the headphone jack to the speaker. Inserting the headphones breaks the connection to the speakers and diverts it to the headphones.