I had the same problem as well for nearly 3 months.
I had tried bring the Iphone into my phone carrier and they sent me to the AppleStore. When I brought it to them they hooked it up to the diagnostic machine and they told me just to restart the Iphone from the factory settings.
This didn't work either. To complicate things more, other "solutions" seem to only yield temporary success. These temporary solutions included: blowing compressed air into every port, various restart combinations, various factory restore methods.
I had nearly given up until I stumbled upon a support post on Apple's website that finally yielded success.
http://support.apple.com/kb/TS1630
The solution for me is listed as line 7, which reads:
"Check the receiver mesh (which is on the top front of the device, above the display). If it appears blocked, use a clean, small, dry, soft-bristled brush to carefully and gently brush away any debris."
Apparently, this cylinder shaped, mesh area is in some way tied to what triggers the headphones/speaker selection. I am not sure how, but I can say that after gently brushing it out my sounds are working again; specifically my music is now able to play directly off the speakers and my Iphone apps all play their sounds agian.
Hope this helps you as well!