Normally I wouldn't post anything as I would have solved my problem via searching, but I could not find anything relating to my problem. Anyway here goes.
My Xperia Z does not produce sound from the loudspeaker on STOCK based roms, other roms such as CM11 and MIUI work perfectly fine. which rules out a hardware fault. The problem is rather weird. Specifically, it is like the phone thinks the earphone is plugged in, therefore all the sounds are being routed to the earphone port and not the speaker. Notification tones sometime work but it its very soft or have like a crackling sound. (Note sound works fine through the earphones). This obviously has an impact on voice calls, the only way I can talk without a headset is via bluetooth headset or to put the loudspeaker on, which then the person comes through the loudspeaker.
This lead me to believe it has something to do with Smart Connect(Liveware), where once the earphone is plugged in the music automatically starts playing, so therefore the app may think the earphone is plugged in 24/7. I deleted the app but still the problem was there.
As I said this is only apparent on stock roms. I flashed unmodded stock via flashtool(4.3) and still same problem, other stock based roms I have tried include Existenz v1.5.5(4.4.2) and BlackZ(4.4.2). However on CM11 roms(4.4.4), MIUI(4.2.2 - 4.4) and ColorOS(4.2.2) the sound works completely fine, except on CM11 the mic randomly stops working but that may be another bug entirely.
I am completely stumped on this and any help would be appreciated. Thank you