You have a ground offset problem. Basically, you are not distinguishing between power ground and signal ground, so offset voltage due to the power current is added to the signal.
Good grounding is not a trivial subject, and there is often not a simple easy answer, especially after the fact.
It would be difficult to describe exactly what to do, even with good diagrams of your setup. One way or another, you have to keep the power supply return currents from flowing thru the wire that is the 0V signal reference between the computer and the class D amp. One way would be to use a separate isolated supply for each device, then connect the grounds only at the signal feed. Since each side is isolated, there would be no return currents flowing thru the link. If the devices don't have separate signal ground connections and you can't get inside them, then you have to treat them as black boxes and the separate isolated supplies is pretty much the best way.
Sorry to not be more specific, but this is actually a rather complicated problem many more details of the setup would have to be known to offer any better suggestions.
I gave you one answer, but I see you edited your post to basically ask the same thing again.
Let me be more clear: Your setup is fundamentally flawed. Hooking up the power like that was a bad idea, because it leads to exactly the problem you are seeing. Some possible solutions:
- Ditch the whole setup, and do it over right. If you don't understand grounding, get someone to do it that does.
- Use separate power supplies for the computer and amp, then tie the grounds together only thru the single audio cable. This is what I suggested above, but you apparently missed.
- Use a audio transformer between the computer and amp. This was suggested by Tim, but you apparently missed that too.
- Have the computer send the data digitally, which is then easy to opto-isolate. Get a amp that can deal with digital data, or add a D/A in front of the amp. While this would work in theory, it's rather a long way to go to get around something that shouldn't be that way in the first place.
The diagram helps. Your experiment with the headphones proves that some of the 5V power supply ground return currents are running thru the ground of the audio cable. This must be avoided.
Why can't a separate 5V supply be powered from whatever is powering the 12V supply? Splice the two line cords together so you have one power plug if that's what you want. Why does it matter that the 5V is coming directly from the AC power as apposed to the 12V DC power for the amp? The advantage is that 5V DC supplies are plentiful and cheap.
If you really need to run the computer from the 12V DC power, then get a isolated DC-DC converter. Those exist, but aren't as plentiful and cheap.
You can also try Tim's idea and use a audio transformer. Be careful with capacitive coupling, and watch the frequency and impedance specs, but if done right should significantly reduce the noise.