录制视频而不停止设备的声音/音乐

时间:2016-08-10 13:12:50

标签: ios swift video avfoundation

我正在使用Swift的AVFoundation在iOS中捕获视频。但是当我使用Apple Music / Spotify播放歌曲然后单击我的应用程序的录制按钮时,它会暂停/停止音乐然后录制视频。我该如何防止这种情况发生?

这是我的代码:

@IBAction func record_video(sender: AnyObject) {
        var initialOutputURL = NSURL(fileURLWithPath: "")

        do
        {
            initialOutputURL = try NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true).URLByAppendingPathComponent("output").URLByAppendingPathExtension("mov")
        }catch
        {
            print(error)
        }
        if !isRecording
        {

            isRecording = true
            if let outputs = captureSession.outputs as? [AVCaptureOutput] {
                for output in outputs {
                    captureSession.removeOutput(output)
                }
            }

            do
            {
                try audioSession.setCategory(AVAudioSessionCategoryAmbient)
            }
            catch
            {
                print("Can't Set Audio Session Category: \(error)")
            }
            AVAudioSessionCategoryOptions.MixWithOthers

            do
            {
                try audioSession.setMode(AVAudioSessionModeVideoRecording)
            }
            catch
            {
                print("Can't Set Audio Session Mode: \(error)")
            }
            // Start Session
            do
            {
                try audioSession.setActive(true)
            }
            catch
            {
                print("Can't Start Audio Session: \(error)")
            }


            UIView.animateWithDuration(0.5, delay: 0.0, options: [.Repeat, .Autoreverse, .AllowUserInteraction], animations: { () -> Void in
                self.record.transform = CGAffineTransformMakeScale(0.75, 0.75)
                }, completion: nil)

            let audioInputDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio)
            do
            {
                let audioInput = try AVCaptureDeviceInput(device: audioInputDevice)

                // Add Audio Input
                if captureSession.canAddInput(audioInput)
                {
                    //captureSession.addInput(audioInput)
                }
                else
                {
                    NSLog("Can't Add Audio Input")
                }

            let videoInput: AVCaptureDeviceInput
            do
            {
                videoInput = try AVCaptureDeviceInput(device: captureDevice)

                // Add Video Input
                if captureSession.canAddInput(videoInput)
                {
                    captureSession.addInput(videoInput)
                }
                else
                {
                    NSLog("ERROR: Can't add video input")
                }
            }
            catch let error
            {
                NSLog("ERROR: Getting input device: \(error)")
            }
            videoFileOutput = AVCaptureMovieFileOutput()
            captureSession.addOutput(videoFileOutput)
            captureSession.sessionPreset = AVCaptureSessionPresetHigh
            captureSession.automaticallyConfiguresApplicationAudioSession = false

            videoFileOutput?.startRecordingToOutputFileURL(initialOutputURL, recordingDelegate: self)


            }
            catch let error
            {
                NSLog("Error Getting Input Device: \(error)")
            }

        }
        else
        {
            isRecording = false

            UIView.animateWithDuration(0.5, delay: 0, options: [], animations: { () -> Void in
                self.record.transform = CGAffineTransformMakeScale(1.0, 1.0)
                }, completion: nil)
            record.layer.removeAllAnimations()
            videoFileOutput?.stopRecording()
        }



    }

请注意,我评论了captureSession.addInput(audioInput)。如果我删除该代码,该应用程序可以录制视频,它不会暂停/停止音乐,但视频输出没有声音。有解决方法吗?

3 个答案:

答案 0 :(得分:2)

您可以参考此Question

的答案

我使用SCRecorder Library实现了相同的功能,但也可以使用AVCaptureSession实现。

答案 1 :(得分:2)

我设法自己解决了这个问题。这一行:AVAudioSessionCategoryOptions.MixWithOthers没有做任何事情。我把它移到了选项中: try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: [AVAudioSessionCategoryOptions.MixWithOthers])

有效!

答案 2 :(得分:0)

这是迅速为我工作的方法,本质上与杰森的答案相同,只是迅速。

将此代码添加到您的

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?){


        add your laucher code
       let audioSession = AVAudioSession.sharedInstance()
    do {
        // Set the audio session category, mode, and options.
        try audioSession.setCategory(.playAndRecord,  options: [.mixWithOthers,.defaultToSpeaker,.allowBluetooth])
        try audioSession.setActive(true)
    } catch {
        print("Failed to set audio session category.")
    }
  }

然后在您设置捕获会话的文件中

   captureSession.automaticallyConfiguresApplicationAudioSession = false

基本上可以与其他对象配合使用,如doc“该选项表明该会话的音频是否与其他音频应用程序的活动会话的音频混合”(https://developer.apple.com/documentation/avfoundation/avaudiosession/categoryoptions)中所说的一样,默认情况下,扬声器使音乐声音更大当与其他选项配合使用时。