14

每当我启动一个以麦克风作为输入运行的 AVCaptureSession 时,它都会取消当前正在运行的任何背景音乐(例如 iPod 音乐)。如果我注释掉添加音频输入的行,则背景音频会继续。

有谁知道在继续播放背景音频的同时用麦克风录制视频剪辑的方法?当您尝试录制视频并且当前正在播放音乐时,也会出现错误。

A试图这样做:

[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
UInt32 doSetProperty = 1;
AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(doSetProperty), &doSetProperty);
[[AVAudioSession sharedInstance] setActive: YES error: nil];

'AudioSessionSetProperty' is deprecated: first deprecated in iOS 7.0

所以我试着这样做:

AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil; 
[audioSession setCategory:AVAudioSessionCategoryPlayback
              withOptions:AVAudioSessionCategoryOptionMixWithOthers
                    error:&setCategoryError];
[audioSession setActive:YES error:nil];

但最后还是不行。感谢帮助!

4

2 回答 2

31

在您的AppDelegate中:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //Stop app pausing other sound.
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord
                                     withOptions:AVAudioSessionCategoryOptionDuckOthers | AVAudioSessionCategoryOptionDefaultToSpeaker
                                           error:nil];
}

您在哪里分配AVCaptureSession

AVCaptureSession *session = [[AVCaptureSession alloc] init];
session.automaticallyConfiguresApplicationAudioSession = NO;

此代码将允许您播放背景音乐并AVCaptureSession使用麦克风运行。

迅速更新:

应用代理

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    //Stop app pausing other sound.
    do{
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, 
                                            withOptions: [.DuckOthers, .DefaultToSpeaker])
    }
    catch {

    }

    return true
}

您在哪里分配AVCaptureSession

let session = AVCaptureSession()
session.automaticallyConfiguresApplicationAudioSession = false
于 2015-01-19T13:48:46.083 回答
19

您可以使用AVAudioSessionCategoryOptionMixWithOthers. 例如,

AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];

之后,您可以AVAudioPlayer同时使用 与AVCaptureSession

但是,上面的代码导致音量非常低。如果您想要正常音量,请使用AVAudioSessionCategoryOptionDefaultToSpeakerwithAVAudioSessionCategoryOptionMixWithOthers如下,

[session setCategory:AVAudioSessionCategoryPlayAndRecord  withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker error:nil];

这进展顺利。

于 2014-04-18T11:22:37.340 回答