Swift IOS使用AVFoundation录制视频和音频 [英] Swift IOS Record Video and Audio with AVFoundation
问题描述
通过遵循此问题,我能够成功获取录制的视频 此处
I was able to successfully grab the recorded video by following this question here
基本上
- 继承自
AVCaptureFileOutputRecordingDelegate
原型 - 遍历可用设备
- 使用相机创建会话
- 开始录制
- 停止记录
- 通过实现上述原型方法获取录制视频
- Inherit from
AVCaptureFileOutputRecordingDelegate
prototype - Loop through available devices
- Creating a session with the camera
- Start Recording
- Stop Recording
- Get the Record video by implementing above prototype's method
但是文件不随音频一起提供.
But the file doesn't comes with the audio.
根据这个问题,我有分别录制音频并使用提到的类合并视频和音频
According to this question, i have to record audio separately and merge the video and audio using mentioned classes
但是我不知道如何同时实现视频和音频录制.
But i have no idea how to implement video and audio recording at the same time.
for device in devices {
// Make sure this particular device supports video
if (device.hasMediaType(AVMediaTypeVideo)) {
// Finally check the position and confirm we've got the back camera
if(device.position == AVCaptureDevicePosition.Back) {
captureDevice = device as? AVCaptureDevice
if captureDevice != nil {
print("Capture device found")
beginSession()
}
}
}
}
在此循环中,仅可用的设备类型为.Front和.Back
in this loop only available device types are .Front and .Back
推荐答案
Found the answer, This answer goes with this code
可以简单地通过
- 声明另一个捕获设备变量
- 循环浏览设备并初始化摄像头和音频捕获设备变量
- 将音频输入添加到会话中
代码
var captureDevice : AVCaptureDevice?
var captureAudio :AVCaptureDevice?
浏览设备并初始化捕获设备
var captureDeviceVideoFound: Bool = false
var captureDeviceAudioFound:Bool = false
// Loop through all the capture devices on this phone
for device in devices {
// Make sure this particular device supports video
if (device.hasMediaType(AVMediaTypeVideo)) {
// Finally check the position and confirm we've got the front camera
if(device.position == AVCaptureDevicePosition.Front) {
captureDevice = device as? AVCaptureDevice //initialize video
if captureDevice != nil {
print("Capture device found")
captureDeviceVideoFound = true;
}
}
}
if(device.hasMediaType(AVMediaTypeAudio)){
print("Capture device audio init")
captureAudio = device as? AVCaptureDevice //initialize audio
captureDeviceAudioFound = true
}
}
if(captureDeviceAudioFound && captureDeviceVideoFound){
beginSession()
}
内部会话
try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
try captureSession.addInput(AVCaptureDeviceInput(device: captureAudio))
这将输出带有音频的视频文件.无需合并音频或执行任何操作.
This will output the video file with audio. no need to merge audio or do anything.
此苹果文档帮助
这篇关于Swift IOS使用AVFoundation录制视频和音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!