The wall is acting just like a sound board which is part of a stringed musical instrument, exciting a larger volume of air and hence producing a louder sound.
When you hit a nail you send (compression) pulses through the nail which are either reflected at the interface between the nail and the medium outside or are transmitted through the interface.
The fraction of the energy transmitted and reflected is determined by a parameter called the acoustic impedance (= density × speed) for the materials either side of an interface and the greater the difference the more sound is relected as compared with the sound transmitted.
With a steel (5800 m/s, 7800 kg/m$^3$) to air (speed of sound 330 m/s, density 1.2 kg/m$^3$) interface there is a very large difference between the acoustic impedances and so most of the sound is reflected within the nail and the little that gets out only exited a small volume of air around the nail.
When the nail is being hammered into a brick (4200 m/s, 1850 kg/m$^3$) wall or any other building material the acoustic impedances across the interface are now much closer to one another so a lot more of the sound is transmitted into the wall.
At the wall to air interface there fraction of sound transmitted from the wall into the air is still small because of the large difference in acoustic impedance but the area of the wall is now large and so more air is excited producing a larger sound.
If you have a tuning fork excite it and listen to the sound that it produces.
Now excite the tuning fork and place its stem on a table - the sound produced vy the fork becomes much louder.
This is because the sound travels from the steel fork to the wooden? table reasonably efficiently (similar acoustic impedances) and then the vibrating table excites a larger volume of air.
If sound is beig produced in one room the walls of the room reflect a lot of the sound so little is transmitted to the next room.
However if the solid parts of a room are made to vibrate (eg when using an electric drill/powered multi-tool those vibrations can be transmitted though the fabric of the building and then can be heard in as a (loud) sound in another room.