Switch microphone to speakerphone mic
I found two apps 
one free - Auto speaker here
Try the free one first

second Tasker - Paid here

It has lots of automating features beside your need.
Before paying for App Read the tutorial first.
To use tasker use this tutorial link

Both apps uses sensors. Try on you device.