Modern earphones are not just (stereo) speakers, but they integrate a microphone and few buttons. All these components are available through a 4-pins 3.5mm plug (also known as TRRS). This schematic shows you how the microphone and buttons are connected through this connector. The common purpose of these buttons is music control, but in general, their behavior depends on the specific application. For example, if the smartphone camera is opened, the volume buttons can be used to shot photos. This idea is also the basis of popular selfie sticks.
As you can see in the schematic, the circuit is elementary, just some resistors and, of course, the buttons. Instead of the real microphone, you must add an equivalent resistor (>1000Ohm, according to Android Specs). Be careful to the values of the resistors, they are not the absolutes values, but the equivalent value read from the plug point-of-view. The full circuit specifications can be read from the [official Android documentation] (https://source.android.com/devices/accessories/headset/plug-headset-spec). It works only for Android since Apple devices require a custom circuitry to enable these functionalities.
You can also observe the circuit I used to create a single-button device to shot photos for a time-lapse of the 3D-printing process.