For reference:
https://godbolt.org/z/Gs5d5W6TrI made some changes to make GCC up to 13 happy. Everything in the output seems to be where it should, despite not using volatiles (not unexpected, the ISR read-modify-writes and it's a short function). Writes to sample and len should be ATOMIC but as long as _delay_ms() is longer than the sample (highly likely) it's not like it's going to be interrupted.
It would help if you explained in what way it "doesn't work"... we're not psychic here!
Q2: Is there any processing to do on the samples them selves or/and during their reproduction to:
- reduce the click at the end of playback.
Set OCR to a final (mid scale) value before disabling interrupts.
- get the Max volume
- get the max quality
Use a DAC. Use higher sample rate.
Q3: Given that the output is already a High Freq PWM modualted with the sound:
- What is the simplest circuit to build a CLASS D amplifier?
can I use a simple MOSFET to drive the loud speaker?
One MOSFET, not really, but a half-bridge yes. You need both so that the output is fully driven (low impedance) at all times. A gate driver chip like TC4420 would probably be fine up to a few hundred mA. Use a series resistor and coupling capacitor to drive the speaker.
Note that you can't disable the carrier entirely without generating a pop, you need to keep it "simmering" between samples. Alternately, make it ramp down slowly over many samples (longer than the RC time constant of the coupling cap (HPF)), so that the transition between 0 and 50% duty is slow enough to not pass the filter. And then back up when a sample is transmitted.
Even just a little ramping may be desirable to turn the pop into a softer click or bump sound.
8 to 64 kSps is probably not a big deal, or, pushing (but not exceeding) the limits of what GCC can do, but you may find if you need to do anything more than fetch samples in the ISR, spare CPU cycles quickly dry up, choppy output or unexpected rate results, and hand tuned ASM is required. Which is easy enough for AVR, it's a simple platform. Before going to ASM, pay close attention to what variables are written and saved in the ISR, order of access, and etc., and minimize manipulation of them. To wit: len could be assigned effptr + length[n], comparison being done on the raw pointer instead of the index. This saves a half dozen instructions already.
Tim