This is called, The Doppler effect.
In short terms, when the trains is farther away the wavelength of the whistles sound are longer and more separate from each other, and more farther away from you, as it gets closer to you, the wavelengths start getting shorter and more louder the closer it gets to you. Basically the wavelengths change because of the motion of the source.