Sound waves are pressure variations in the air. In a moving-coil microphone these variations hit a thin, flexible diaphragm and make it vibrate. The diaphragm is attached to a coil that sits in the field of a permanent magnet, so the coil moves back and forth and cuts the field lines. By electromagnetic induction, a potential difference is induced in the coil. This gives an alternating electrical signal with the same frequency as the sound. A louder sound moves the diaphragm further, so the signal has a larger amplitude.
A loudspeaker works in reverse. The alternating current from an amplifier flows in a coil attached to a paper or plastic cone, and the coil sits in the field of a permanent magnet. A current-carrying conductor in a magnetic field feels a force (the motor effect). Because the current keeps reversing, the force on the coil reverses too, so the coil and cone vibrate backwards and forwards. The cone pushes on the air and creates pressure variations: sound waves with the same frequency as the current.
Headphones use exactly the same principle as a loudspeaker, only smaller. A higher frequency current makes a higher pitched sound, and a larger current makes a louder one.