ответ

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

Вам также нужно настроить аудио сеанс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)") 
    } 

Теперь для видеозаписи. Вы будете использовать AVCaptureSession. Объявите следующие как глобальные переменные:

let captureSession = AVCaptureSession() 
var currentDevice: AVCaptureDevice? 
var videoFileOutput: AVCaptureMovieFileOutput? 
var cameraPreviewLayer: AVCaptureVideoPreviewLayer? 

Затем настройте сессию в 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) 

Затем вы создаете @IBAction для обработки когда пользователь нажимает кнопку записи (я использовал только простую кнопку, которую я сделал красный и круглый):

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

Тогда все, что осталось для вас сделать, это сохранить видео в (предположительно) Фотопленку , Но я не буду включать это. Вы должны приложить некоторые усилия. (Подсказка: UISaveVideoAtPathToSavedPhotosAlbum)

Так вот, это люди. Вот как вы используете AVFoundation для записи видео и воспроизведения музыки из библиотеки одновременно.