AVAudioSession:通过耳机扬声器播放音频 [英] AVAudioSession : Playing audio through earpiece speaker

查看:901
本文介绍了AVAudioSession:通过耳机扬声器播放音频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图通过耳机扬声器播放音频并且工作正常。相同的代码在以下情况下不起作用。

I am trying to play an audio through earpiece speaker and it is working fine. The same code is not working in following situation.


  1. 打开相机录制视频

  2. 取而代之开始录音,取消它

  3. 然后,试图通过听筒播放音频不工作。它通过主音箱播放

这是我通过耳机播放音频的代码。

Here is my code to play audio through earpiece.

-(void)initialAVaudioPlayer
{
    if (player==nil) {
        NSError *error = nil;
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
        [session setActive: YES error:nil];

        AVAudioSessionPortDescription *routePort = session.currentRoute.outputs.firstObject;
        NSString *portType = routePort.portType;

        if ([portType isEqualToString:@"Receiver"]) {
            [session  overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];
        } else {
            [session  overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:&error];
        }        


        NSString *path;
        NSError *err;
        NSString *name;
        name = @"referenceaudio";
        path = [[NSBundle mainBundle] pathForResource:name ofType:@"wav"];
        if ([[NSFileManager defaultManager]fileExistsAtPath:path]) {
            NSURL *url = [NSURL fileURLWithPath:path];
            player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&err];
            if (!err) {
                player.numberOfLoops = -1;

            }
            else{
                //NSLog(@"%@",[err description]);
            }

        }
    }
}

这是代码,当用户按下取消时,

Here is code, while user press cancel ,

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    NSLog(@"here");
    [self dismissViewControllerAnimated:YES completion:nil];
}


推荐答案

更改取消按钮的音频路线解决问题

Change audio route for cancel button solve the problem

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    NSError *error = nil;
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:&error];
    [session  overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
    [session setActive: YES error:nil];

    videoPicker = nil;
    [self dismissViewControllerAnimated:YES completion:nil];
}

这篇关于AVAudioSession:通过耳机扬声器播放音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆