Not sure of a code fix, but one thing that has caused that to happen with me are:
1. Cell Phone signals cause speakers to crackle, though this isn't likely as it is consistent.
2. More likely, devices that are activated near where your speakers are plugged in. For example, I have a game pad that I plugged in to the front of my computer. My speakers were also plugged in in front (long story) and the game pad started to cause the speakers to crackly constantly.
Since your problem is only in specific situations, try plugging your speakers into a different port if you have one. If that works, check any newly installed hardware, be it usb or internal. Try replacing them with older parts or omitting them all together to see if it fixes the problems. If it is, then the problem is that it is drawing too much current, thus creating a magnetic field which creates a current in your speaker wires. There probably is a better solution that just moving your speakers, but I don't know what it is.
Ever notice how in Microsoft word, the word "microsoft" is auto corrected to be "Microsoft" but "macintosh" just gets the dumb red underline?