如何通过内置的耳机扬声器播放音频 [英] How to play audio through built-in earpiece speaker
问题描述
我已经看到一些类似WhatsApp的应用程序具有一项功能,当用户将设备靠近耳边时,它只能通过听筒(电话扬声器)播放音频剪辑.否则,它将通过普通的内置扬声器播放.
I have seen some apps like WhatsApp has a feature to play audio clips only through earpiece(phone call speaker) when the user brings up the device near to ear. Otherwise its playing via normal built-in speaker.
我正在使用MPMoviePlayer播放音频剪辑.
I am using MPMoviePlayer for playing audio clips.
我确实在互联网上经历了很多类似的问题和答案,所有答案都表明将AudioSession类别设置为PlayAndRecord.而已.
I did go through lots of similar questions and answers on the internet, and all the answers say to set the AudioSession Category to PlayAndRecord. Thats it.
我做了同样的事情,但是无法获得我想要得到的确切结果.
I did the same, but couldn't get the exact result that I want to get.
// Audio Player
self.audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[audioSession setActive:YES error:nil];
self.moviePlayer = [[MPMoviePlayerController alloc] init];
self.moviePlayer.view.hidden = YES;
// AVAudioSessionPortDescription *routePort = self.audioSession.currentRoute.outputs.firstObject;
// NSString *portType = routePort.portType;
//
// if ([portType isEqualToString:@"Receiver"]) {
// [self.audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
// } else {
// [self.audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
// }
任何人都可以告诉我如何以及在哪里修改声音源,以便仅在用户拿起设备时通过听筒扬声器播放音频吗?
Can anyone please show me how and where can I modify the source to play audio through the earpiece speaker only when the user brings up the device?
推荐答案
我可以使用AVAudioSession和ProximityMonitering
I could do it using AVAudioSession and ProximityMonitering
- (void)viewDidLoad {
[super viewDidLoad];
[UIDevice currentDevice].proximityMonitoringEnabled = YES;
if ([UIDevice currentDevice].proximityMonitoringEnabled == YES) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(proximityChanged:)
name:@"UIDeviceProximityStateDidChangeNotification"
object:[UIDevice currentDevice]];
}
}
- (void) proximityChanged:(NSNotification *)notification {
UIDevice *device = [notification object];
NSLog(@"In proximity: %i", device.proximityState);
if(device.proximityState == 0){
[audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
}
else{
[audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
}
}
播放音频
audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[audioSession setActive:YES error:nil];
AVAudioSessionPortDescription *routePort = audioSession.currentRoute.outputs.firstObject;
NSString *portType = routePort.portType;
NSLog(@"PortType %@", portType);
if ([portType isEqualToString:@"Receiver"]) {
[audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
}
这篇关于如何通过内置的耳机扬声器播放音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!