LM386 motorboating that goes away with a resistor in parallel with the bypass capacitor on pin 7
The main problem is that you have the gain of the LM386 set much too high.
By putting a capacitor (C1) between pin 1 and 8 you have set the gain to 200 times. If the input signal is coming straight from a digital pin on the processor with 3.3V output you only need a gain of 2 at most.
With a gain of 200 the LM386 is amplifying small signals coming from the digital pin to an audible level.
Even if you remove C1 the gain will still be 20 times - you will need to attenuate the signal from the processor by about 10-11 times to avoid overloading the amplifier. A 10k resistor in series with the input and a 1k resistor to ground will achieve that. Even better would be a potentiometer to adjust the volume.
Your current solution is drastically altering the biasing of the LM386 such that it is not a linear amplifier, the digital signal is still able to break through the LM386 to drive the speaker but small noise signals do not. Please see page 1 of the data sheet LM386 datasheet
If you only need to drive the speaker with a square wave then you may not even need an amplifier. For low volume just a capacitor and resistor in series driving the speaker will function (for example a 47 ohm resistor and a 10uF capacitor). The resistor is to avoid overloading the digital output with the low resistance of the speaker while the capacitor removes the DC offset since the digital output is always positive (either 0V or 3.3V).