The piezo speaker can be used either as an input or an output. It is an electronic component made from a combination of two discs of different materials. One is metallic while the other is generally ceramic and both have piezoelectric properties. When a voltage is applied to these materials, they repel and produce an audible click. Removing the voltage difference, the materials will return to their original position causing another click. By quickly switching between applying and removing voltage to the piezo, different tones can be generated. Read more about how to play melodies with the piezo here.
Knocking on a piezo makes the materials inside vibrate, thus producing a voltage. When the piezo is connected to an analog pin, this voltage can be read just like from any other analog input. Read more about using the piezo as a knock sensor here.