This example makes use of a Piezo Speaker in order to play melodies. We are taking advantage of the processors capability to produde (sic) PWM signals in order to play music.
That's a direct quote (including the misspelling of "produce") from
http://www.arduino.cc/en/Tutorial/PlayMelodyThe first example does not use PWM, it just wiggles a pin at the approximate frequency of a desired note. Any old pin will do. (In case you can't follow the code, the clue that it isn't Arduino-style PWM is that there are no
analogWrite function calls.)
The second example attempts to use analogWrite as a (fixed) volume control. That is if you use a smaller number in the analogWrite function call you should get a lower volume. If you use a non-PWM pin for the second example, you will have two values of volume: Maximum volume and zero volume.
The way that it tries to do the volume control is that instead of wiggling the pin between a solid +5 Volts and 0 Volts, it turns on bursts of PWM at the wiggle rate. The higher frequency components of the PWM are (presumably) filtered out by the speaker characteristics and/or by the human auditory response limits with the result that it is kind of like wiggling the output pin at the audio rate of the desired tone but with a lower effective amplitude.
Looking at the comments in the program, I wouldn't expect this to be a very practical program for actually playing tunes, but it can still be a learning experience. (Or, maybe, not.) See Footnote.
Regards,
Dave
Footnote:The analogWrite function takes an eight-bit argument. If you try to feed it a value of 500 as is done in the example, it actually gets just the lower 8 bits (value of 244 decimal). I'm not sure what beginners are supposed to get out of this kind of confusingly shaky example. Anyhow, try it example number 2 with analogWrite values like 50, 100, 150, 200 (instead of 500) and see what it sounds like.