This is what happens. Consider a narrow "beam" of sound. Sound doesn't travel in beams, but I just want to look at a part of the overall picture.Imagine the beam starts in warm air and goes into a region of cool air:
I've drawn two situations. In the first, the beam crosses the boundry between warm and cool at a right angle. All that happens is the wavelength changes. It gets shorter, since the speed of sound is lower in the cool air.
Now look at the beam that strikes the boundry at an angle.The wavefront that has just crossed actually has two wavelengths; long for the part still in the warm air, short for the part in the cold.This makes it skewed. All later waves just propagate off this crooked wavefront, in a new direction.
This effect is more pronounced for long wavelengths, which is why foghorns are low pitched.