>I have successfully written the code<
Are you sure? I assume you know the regular Arduino doesn’t have a true-analog output?
Have you tried TMRpcm? It “fakes” PCM/analog with fast PWM, but you still won’t get “CD quality”.
You might want to try your code (or TMRpcm) with regular powered computer speakers so you can test & debug the hardware & software separately. DON’T connect your home stereo because unfiltered PWM can do “bad things” to an analog amplifier. (Also “be careful” if you have expensive computer speakers.)
And/or test the LM386 circuit with your phone or computer as a sound source.
>but get very quiet and bad sound from the speaker.<
Try taking-out the 100 Ohm resistor. And reduce the base resistor to around 200 Ohms. It’s still not a linear-analog amplifier circuit but it can work with PWM (TMRpcm).