Reputation: 601
I don't seem to be able to find anything useful regarding this topic.
When using the AVAudioPlayer, the app randomly starts playing the audio through the speaker (earpiece) instead of the loudspeaker. When this happens, even YouTube videos streamed from YouTube directly through a UIWebView play using the earpiece.
Does anyone know how to switch the output source?
Upvotes: 3
Views: 875
Reputation: 37985
If you are also using the mic to record, here's how to switch the output device back to the speaker/headphones instead of the earpiece (Swift 4):
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryMulti)
} catch let error {
print("\(error.localizedDescription)")
}
I found AVAudioSessionCategoryMulti
works better over AVAudioSessionCategoryPlayAndRecord
as the latter defaults output to the earpiece rather than the speakers, yet it is also the default category when you enable the mic (go figure).
Upvotes: 0
Reputation: 37
Its not possible to play a audio file through the iPhone speakers even if headphones are plugged in?
But we can get notified about when the output device are plugged in or out and accordingly we can do our stuff. below is the code for your reference .
void audioRouteChangeListenerCallback (void *inUserData, AudioSessionPropertyID inPropertyID, UInt32 inPropertyValueSize, const void *inPropertyValue) {
if (inPropertyID != kAudioSessionProperty_AudioRouteChange) return;
MPMusicPlayerController *controller = (__bridge MPMusicPlayerController *)inUserData;
CFDictionaryRef routeChangeDictionary = inPropertyValue;
CFNumberRef routeChangeReasonRef = CFDictionaryGetValue(routeChangeDictionary, CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
SInt32 routeChangeReason;
CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
CFStringRef oldRouteRef = CFDictionaryGetValue(routeChangeDictionary, CFSTR (kAudioSession_AudioRouteChangeKey_OldRoute));
NSString *oldRouteString = (__bridge NSString *)oldRouteRef;
if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable) {
if ((controller.playbackState == MPMusicPlaybackStatePlaying) &&
(([oldRouteString isEqualToString:@"Headphone"]) ||
([oldRouteString isEqualToString:@"LineOut"])))
{
// Janking out the headphone will stop the audio.
[controller pause];
}
}
Upvotes: 2