原本打算原生写,感觉太复杂了,还是用插件吧~
下载地址 :
官网API介绍地址 :https://olokobayusuf.github.io/NatCorder-Docs/
插件中包含两个案例,一个是打开摄像头录屏(同时录制声音),一个是灰度摄像头视频录制,还可以保存为gif和mp4两种不同格式,我只用到了视频录制,因此本文也只简介此功能
RecordButton脚本 : 主要是检测按钮的按下和抬起,并调用绑定的 onTouchDown, onTouchUp
/*
* NatCorder
* Copyright (c) 2018 Yusuf Olokoba
*/
namespace NatCorderU.Examples {
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
[RequireComponent(typeof(EventTrigger))]
public class RecordButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
public Image button, countdown;
public UnityEvent onTouchDown, onTouchUp;
private bool pressed;
private const float MaxRecordingTime = 10f; // Seconds
private void Start () {
Reset ();
}
private void Reset () {
// Reset fill amounts
if (button) button.fillAmount = 1.0f;
if (countdown) countdown.fillAmount = 0.0f;
}
void IPointerDownHandler.OnPointerDown (PointerEventData eventData) {
// Start counting
StartCoroutine (Countdown ());
}
void IPointerUpHandler.OnPointerUp (PointerEventData eventData) {
// Reset pressed
pressed = false;
}
private IEnumerator Countdown () {
pressed = true;
// First wait a short time to make sure it's not a tap
yield return new WaitForSeconds(0.2f);
if (!pressed) yield break;
// Start recording
if (onTouchDown != null) onTouchDown.Invoke();
// Animate the countdown
float startTime = Time.time, ratio = 0f;
while (pressed && (ratio = (Time.time - startTime) / MaxRecordingTime) < 1.0f) {
countdown.fillAmount = ratio;
button.fillAmount = 1f - ratio;
yield return null;
}
// Reset
Reset();
// Stop recording
if (onTouchUp != null) onTouchUp.Invoke();
}
}
}
而绑定的两个函数正是开始录制和停止录制 :
参考 :