如何通过内置耳机扬声器播放音频

时间:2015-07-29 06:17:09

标签: ios objective-c iphone mpmovieplayercontroller avaudiosession

我看到像WhatsApp这样的应用程序有一项功能,即当用户将设备靠近耳朵时,只能通过听筒(电话扬声器)播放音频剪辑。否则它通过普通的内置扬声器播放。

我正在使用MPMoviePlayer播放音频片段。

我确实在互联网上经历了许多类似的问题和答案,并且所有答案都说将AudioSession类别设置为PlayAndRecord。而已。

我做了同样的事,但无法得到我想要的确切结果。

// 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];
//    }

任何人都可以告诉我,只有当用户打开设备时,我才能通过耳机扬声器修改音源以便播放音频吗?

1 个答案:

答案 0 :(得分:5)

我可以使用AVAudioSession和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];
}