ToneMelody works on any pin

This example makes use of a Piezo Speaker in order to play melodies. We are taking advantage of the processors capability to produde PWM signals in order to play music.

But I've noticed I can set the speakerPin to any digital pin, not just the ones with PWM
???

Did you try on the hardware to see if it works? It shouldn't, at least not in a regular Arduino, which has PWM only on a few selected pins.

The PWM is a built-in function of the ATMEGA-328 chip. It is one of the modes that the timer can be set to run in. This means that it is hard-wired to toggle one of the pwm pins, in the actual hardware of the chip.

The tone functions use the timer in a mode that when it overflows above a certain number, it triggers a function. This is a software application, because it is inside this function that the pin (any pin, not just PWM pin) is toggled. It is not a specific hardware feature of the chip.

I think this is correct, and that it answers your question.

SouthernAtHeart:

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/PlayMelody

The 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.