如何同时录制视频和播放音频(快速教程)

Law*_*413 4 avfoundation avaudioplayer mpmusicplayercontroller ios swift

所以,你想录制视频播放音乐从用户的库在同一时间?不要再犹豫了.以下是答案.

Law*_*413 6

对于您将使用的音频播放AVAudioPlayer.您所要做的就是声明AVAudioPlayer全局变量(我将其命名为audioPlayer)并实现下面的代码.

在用户选择他/她想要播放的歌曲后使用此功能:

func mediaPicker(mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {
    let pickerItem: MPMediaItem = mediaItemCollection.items[0]
    let songURL = pickerItem.valueForProperty(MPMediaItemPropertyAssetURL)
    if let sURL = songURL as? NSURL
    {
        songTitle = pickerItem.title!
        do
        {
            audioPlayer = try AVAudioPlayer(contentsOfURL: sURL)
        }
        catch
        {
            print("Can't Create Audio Player: \(error)")
        }
    }
    dismissViewControllerAnimated(true, completion: { () -> Void in
        audioPlayer.play()
    })
}
Run Code Online (Sandbox Code Playgroud)

您还需要设置音频会话(in viewDidLoad).如果您想在录制时播放音频,这一点至关重要:

 // Audio Session Setup
    do
    {
        try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
    }
    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)")
    }
Run Code Online (Sandbox Code Playgroud)

现在进行视频录制.你会用的AVCaptureSession.将以下内容声明为全局变量:

let captureSession = AVCaptureSession()
var currentDevice: AVCaptureDevice?
var videoFileOutput: AVCaptureMovieFileOutput?
var cameraPreviewLayer: AVCaptureVideoPreviewLayer?
Run Code Online (Sandbox Code Playgroud)

然后配置会话viewDidLoad.注意:视频预览位于容器中,整个视频相关代码位于不同的视图控制器中,但只使用视图而不是容器应该可以正常工作:

// Preset For 720p
captureSession.sessionPreset = AVCaptureSessionPreset1280x720

// Get Available Devices Capable Of Recording Video
let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as! [AVCaptureDevice]

// Get Back Camera
for device in devices
{
    if device.position == AVCaptureDevicePosition.Back
    {
        currentDevice = device
    }
}
let camera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

// Audio Input
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")
    }
}
catch let error
{
    NSLog("Error Getting Input Device: \(error)")
}

// Video Input
let videoInput: AVCaptureDeviceInput
do
{
    videoInput = try AVCaptureDeviceInput(device: camera)

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

// Video Output
videoFileOutput = AVCaptureMovieFileOutput()
captureSession.addOutput(videoFileOutput)

// Show Camera Preview
cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
view.layer.addSublayer(cameraPreviewLayer!)
cameraPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
let width = view.bounds.width
cameraPreviewLayer?.frame = CGRectMake(0, 0, width, width)

// Bring Record Button To Front & Start Session
view.bringSubviewToFront(recordButton)
captureSession.startRunning()
print(captureSession.inputs)
Run Code Online (Sandbox Code Playgroud)

然后@IBAction在用户按下录制按钮时创建一个for handling(我只使用了一个简单的按钮,我将其设置为红色和圆形):

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

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

        videoFileOutput?.startRecordingToOutputFileURL(initialOutputURL, recordingDelegate: self)
    }
    else
    {
        isRecording = false

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

然后你要做的就是将视频保存到(大概)相机胶卷.但我不会包括那个.你必须付出一些努力.(提示:UISaveVideoAtPathToSavedPhotosAlbum)

这就是人们.这就是你AVFoundation用来录制视频和同时播放音乐库的方式.