This has just happened to me after upgrading my phone. I read that if cleaning doesn't work, then you need to do a factory reset. Went through all the hassle of a factory reset and restoring my phone to how it was, then found out that the music still played out of the speakers - total waste of time.
Someone suggested an app called Sound About. In Sound About you can configure where you want your media sound to play, i.e. speakers, headphones, etc. It seems that in my case, the fault was the phone wasn't recognising the fact that the headphones were plugged in and so it didn't switch the sound to the headphones. So now I use the Sound About widget to toggle the sound to go through the headphones, I know it is manual, but at least I can use the headphones again.
I wish I had known this before I did the factory reset. It is worth trying the app (48 hours free trial) before you do anything too drastic.