【问题标题】:Recording a Video without stopping sound/music from device在不停止设备声音/音乐的情况下录制视频
【发布时间】:2016-08-10 13:12:49
【问题描述】:

我正在使用 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)。如果我删除该代码,该应用程序能够录制视频,它不会暂停/停止音乐,但视频输出没有声音。有解决办法吗?

【问题讨论】:

    标签: ios swift video avfoundation


    【解决方案1】:

    我设法自己解决了这个问题。这条线:AVAudioSessionCategoryOptions.MixWithOthers 什么都不做。我将其移至选项: try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: [AVAudioSessionCategoryOptions.MixWithOthers])

    成功了!

    【讨论】:

      【解决方案2】:

      你可以参考这个Question的答案

      我已经使用 SCRecorder 库实现了相同的功能,但也可以使用 AVCaptureSession 来实现。

      【讨论】:

      • 我收到Can't Set Audio Session Mode: Error Domain=NSOSStatusErrorDomain Code=-50 "(null)"' and Can't add video input` 添加后:self.captureSession.automaticallyConfiguresApplicationAudioSession = false;
      【解决方案3】:

      这对我来说是 swift 的,它与 jayson 的回答基本相同,但适用于 swift。

      将此代码添加到您的

          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
      

      基本上 mixwithother 作品正如它在文档中所说的“指示来自此会话的音频是否与来自其他音频应用程序中的活动会话的音频混合的选项”(https://developer.apple.com/documentation/avfoundation/avaudiosession/categoryoptions)并且默认为扬声器允许音乐在工作时更响亮与其他选项混合使用。

      【讨论】:

      • 这有助于在相机打开时在后台播放音乐。你能告诉我如何在录制视频时录制背景音乐和麦克风吗?目前,麦克风只会在没有背景音乐播放时录音。如果正在播放背景音乐,则它没有录制任何内容。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      相关资源
      最近更新 更多