简体   繁体   中英

Recording a Video without stopping sound/music from device

I am working with Swift's AVFoundation to capture a video in iOS. But when I play a song using Apple Music/Spotify then click the record button of my app, it pauses/stops the music then records the video. How do I prevent that from happening?

Here's my code:

@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()
        }



    }

Notice that I commented out captureSession.addInput(audioInput) . If I remove that code, the app is able to record the video, it doesn't pause/stop the music but the video output has no sound. Is there a workaround for this?

I managed to solve the issue on my own. The line: AVAudioSessionCategoryOptions.MixWithOthers doesn't do anything. I moved it to the options: try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: [AVAudioSessionCategoryOptions.MixWithOthers])

It worked!

You can refer to the answer of this Question

I have implemented same feature using SCRecorder Library, but can be achieve with AVCaptureSession as well.

here is what worked for me in swift, it is essentially the same thing as jayson's answer but for swift.

add this code in your

    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.")
    }
  }

then in the file where your set up your capturesession

   captureSession.automaticallyConfiguresApplicationAudioSession = false

essentially mixwithother works as it says in the doc "option that indicates whether audio from this session mixes with audio from active sessions in other audio apps" ( https://developer.apple.com/documentation/avfoundation/avaudiosession/categoryoptions ) and default to speakers allows the music to come out louder when working with the mix with others options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM