Swift3でカメラ起動 – Xcode9
環境
- Swift
- Swift3
- Xcode
- Xcode9
- NSMicrophoneUsageDescription
- Info.plist
- AVFoundation
- AssetsLibrary
備考
カメラへのアクセスのためのInfo.plistの書き方はここを参照
実装
//
// ViewController.swift
// Shoot movies Swift3
//
// Created by ryosuke-hujisawa on 2017/10/06.
// Copyright © 2017年 ryosuke-hujisawa. All rights reserved.
//
import UIKit
import AVFoundation
import AssetsLibrary
class ViewController: UIViewController {
// ビデオのアウトプット
private var myVideoOutput: AVCaptureMovieFileOutput!
// ビデオレイヤー
private var myVideoLayer: AVCaptureVideoPreviewLayer!
// ボタン
private var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// セッションの作成
let session = AVCaptureSession()
// 出力先を生成
let myImageOutput = AVCapturePhotoOutput()
// バックカメラを取得
let camera = AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .back)
let videoInput = try! AVCaptureDeviceInput.init(device: camera!)
// ビデオをセッションのInputに追加
session.addInput(videoInput)
// マイクを取得
let mic = AVCaptureDevice.default(.builtInMicrophone, for: AVMediaType.audio, position: .unspecified)
let audioInput = try! AVCaptureDeviceInput.init(device: mic!)
// オーディオをセッションに追加
session.addInput(audioInput)
// セッションに追加
session.addOutput(myImageOutput)
// 動画の保存
myVideoOutput = AVCaptureMovieFileOutput()
// ビデオ出力をOutputに追加
session.addOutput(myVideoOutput)
// 画像を表示するレイヤーを生成
myVideoLayer = AVCaptureVideoPreviewLayer.init(session: session)
myVideoLayer?.frame = self.view.bounds
myVideoLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
// Viewに追加
self.view.layer.addSublayer(myVideoLayer!)
// セッション開始.
session.startRunning()
// UI
button = UIButton(frame: CGRect(x: 0, y: 0, width: 120, height: 50))
button.backgroundColor = .red
button.layer.masksToBounds = true
button.setTitle("START", for: .normal)
button.layer.cornerRadius = 20.0
button.layer.position = CGPoint(x: self.view.bounds.width/2, y:self.view.bounds.height-50)
button.addTarget(self, action: #selector(ViewController.onTapButton), for: .touchUpInside)
self.view.addSubview(button)
}
@objc internal func onTapButton(sender: UIButton){
print("撮影!")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}