啟用攝影機存取功能
必須宣告「網路攝影機」功能,應用程式才能使用 相機。
- 在 Unity 編輯器中,導覽至「編輯>專案設定>播放器」頁面,前往播放器設定
- 選擇“Windows 應用商店”選項卡
- 在「發佈設定 > 功能」部分中,檢查 網路攝影機 和 麥克風 功能
相機一次只能進行一次操作。 您可以檢查相機目前在 Unity 2018 及更早版本或 UnityEngine.Windows.WebCam.Mode Unity 2019 及更高版本中所處UnityEngine.XR.WSA.WebCam.Mode的模式。 可用的模式有照片、視頻或無。
照片拍攝
Unity 2019 之前的命名空間 () :UnityEngine.XR.WSA.WebCam
Unity 2019 和更新版本 (命名空間) :UnityEngine.Windows.WebCam
類型:PhotoCapture
PhotoCapture 類型可讓您使用相片攝影機拍攝靜態相片。 使用 PhotoCapture 拍照的一般模式如下:
- 建立 PhotoCapture 物件
- 使用您想要的設定建立 CameraParameters 物件
- 透過 StartPhotoModeAsync 啟動相片模式
- 拍攝您想要的照片
- (可選) 與該圖片互動
- 停止照片模式並清理資源
PhotoCapture 的常見設定
對於所有三種用途,請從上述相同的前三個步驟開始
首先建立 PhotoCapture 物件
private void Start()
{
PhotoCapture.CreateAsync(false, OnPhotoCaptureCreated);
}
接下來,存儲您的對象,設置參數,然後啟動照片模式
private PhotoCapture photoCaptureObject = null;
void OnPhotoCaptureCreated(PhotoCapture captureObject)
{
photoCaptureObject = captureObject;
Resolution cameraResolution = PhotoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();
CameraParameters c = new CameraParameters();
c.hologramOpacity = 0.0f;
c.cameraResolutionWidth = cameraResolution.width;
c.cameraResolutionHeight = cameraResolution.height;
c.pixelFormat = CapturePixelFormat.BGRA32;
captureObject.StartPhotoModeAsync(c, false, OnPhotoModeStarted);
}
最後,您還將使用此處提供的相同清理代碼
void OnStoppedPhotoMode(PhotoCapture.PhotoCaptureResult result)
{
photoCaptureObject.Dispose();
photoCaptureObject = null;
}
完成這些步驟後,您可以選擇要拍攝的照片類型。
將相片擷取至檔案
最簡單的操作是將照片直接捕獲到文件中。 照片可以保存為 JPG 或 PNG。
如果您成功啟動照片模式,請拍攝照片並將其儲存在磁碟上
private void OnPhotoModeStarted(PhotoCapture.PhotoCaptureResult result)
{
if (result.success)
{
string filename = string.Format(@"CapturedImage{0}_n.jpg", Time.time);
string filePath = System.IO.Path.Combine(Application.persistentDataPath, filename);
photoCaptureObject.TakePhotoAsync(filePath, PhotoCaptureFileOutputFormat.JPG, OnCapturedPhotoToDisk);
}
else
{
Debug.LogError("Unable to start photo mode!");
}
}
將照片捕獲到磁盤後,退出照片模式,然後清理您的對象
void OnCapturedPhotoToDisk(PhotoCapture.PhotoCaptureResult result)
{
if (result.success)
{
Debug.Log("Saved Photo to disk!");
photoCaptureObject.StopPhotoModeAsync(OnStoppedPhotoMode);
}
else
{
Debug.Log("Failed to save Photo to disk");
}
}
將照片捕獲到帶有位置的 Texture2D
將資料擷取至 Texture2D 時,程式類似於擷取至磁碟。
請按照上述設定程序進行操作。
在 OnPhotoModeStarted 中,將畫面擷取至記憶體。
private void OnPhotoModeStarted(PhotoCapture.PhotoCaptureResult result)
{
if (result.success)
{
photoCaptureObject.TakePhotoAsync(OnCapturedPhotoToMemory);
}
else
{
Debug.LogError("Unable to start photo mode!");
}
}
然後,您將結果套用至紋理,並使用上述常見的清理程式碼。
void OnCapturedPhotoToMemory(PhotoCapture.PhotoCaptureResult result, PhotoCaptureFrame photoCaptureFrame)
{
if (result.success)
{
// Create our Texture2D for use and set the correct resolution
Resolution cameraResolution = PhotoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();
Texture2D targetTexture = new Texture2D(cameraResolution.width, cameraResolution.height);
// Copy the raw image data into our target texture
photoCaptureFrame.UploadImageDataToTexture(targetTexture);
// Do as we wish with the texture such as apply it to a material, etc.
}
// Clean up
photoCaptureObject.StopPhotoModeAsync(OnStoppedPhotoMode);
}
可定位相機
若要將此紋理放在場景中,並使用可定位的相機矩陣來顯示它,請在檢查中result.success將下列程式碼新增至 OnCapturedPhotoToMemory:
if (photoCaptureFrame.hasLocationData)
{
photoCaptureFrame.TryGetCameraToWorldMatrix(out Matrix4x4 cameraToWorldMatrix);
Vector3 position = cameraToWorldMatrix.GetColumn(3) - cameraToWorldMatrix.GetColumn(2);
Quaternion rotation = Quaternion.LookRotation(-cameraToWorldMatrix.GetColumn(2), cameraToWorldMatrix.GetColumn(1));
photoCaptureFrame.TryGetProjectionMatrix(Camera.main.nearClipPlane, Camera.main.farClipPlane, out Matrix4x4 projectionMatrix);
}
Unity 在其論壇上提供了將投影矩陣應用於特定著色器的範例程式碼。
拍攝照片並與原始位元組互動
若要與記憶體畫面的原始位元組互動,請遵循與上述相同的設定步驟和 OnPhotoModeStarted ,就像將相片擷取至 Texture2D 一樣。 不同之處在於 OnCapturedPhotoToMemory 中,您可以在其中取得原始位元組並與它們互動。
在此範例中,您將建立清單,以透過 SetPixels 進一步處理或套用至紋理 ()
void OnCapturedPhotoToMemory(PhotoCapture.PhotoCaptureResult result, PhotoCaptureFrame photoCaptureFrame)
{
if (result.success)
{
List<byte> imageBufferList = new List<byte>();
// Copy the raw IMFMediaBuffer data into our empty byte list.
photoCaptureFrame.CopyRawImageDataIntoBuffer(imageBufferList);
// In this example, we captured the image using the BGRA32 format.
// So our stride will be 4 since we have a byte for each rgba channel.
// The raw image data will also be flipped so we access our pixel data
// in the reverse order.
int stride = 4;
float denominator = 1.0f / 255.0f;
List<Color> colorArray = new List<Color>();
for (int i = imageBufferList.Count - 1; i >= 0; i -= stride)
{
float a = (int)(imageBufferList[i - 0]) * denominator;
float r = (int)(imageBufferList[i - 1]) * denominator;
float g = (int)(imageBufferList[i - 2]) * denominator;
float b = (int)(imageBufferList[i - 3]) * denominator;
colorArray.Add(new Color(r, g, b, a));
}
// Now we could do something with the array such as texture.SetPixels() or run image processing on the list
}
photoCaptureObject.StopPhotoModeAsync(OnStoppedPhotoMode);
}
視訊擷取
Unity 2019 之前的命名空間 () :UnityEngine.XR.WSA.WebCam
Unity 2019 和更新版本 (命名空間) :UnityEngine.Windows.WebCam
類型:VideoCapture
VideoCapture 的功能與 PhotoCapture 類似。 唯一的兩個差異是您必須指定每秒幀數 (FPS) 值,並且只能直接儲存為 .mp4 檔案。 使用 VideoCapture 的步驟如下:
- 建立 VideoCapture 物件
- 使用您想要的設定建立 CameraParameters 物件
- 透過 StartVideoModeAsync 啟動視訊模式
- 開始錄製視頻
- 停止錄製視頻
- 停止視訊模式並清理資源
首先建立我們的 VideoCapture 物件 VideoCapture m_VideoCapture = null;
void Start ()
{
VideoCapture.CreateAsync(false, OnVideoCaptureCreated);
}
接下來,設定您想要錄製的參數並開始。
void OnVideoCaptureCreated(VideoCapture videoCapture)
{
if (videoCapture != null)
{
m_VideoCapture = videoCapture;
Resolution cameraResolution = VideoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();
float cameraFramerate = VideoCapture.GetSupportedFrameRatesForResolution(cameraResolution).OrderByDescending((fps) => fps).First();
CameraParameters cameraParameters = new CameraParameters();
cameraParameters.hologramOpacity = 0.0f;
cameraParameters.frameRate = cameraFramerate;
cameraParameters.cameraResolutionWidth = cameraResolution.width;
cameraParameters.cameraResolutionHeight = cameraResolution.height;
cameraParameters.pixelFormat = CapturePixelFormat.BGRA32;
m_VideoCapture.StartVideoModeAsync(cameraParameters,
VideoCapture.AudioState.None,
OnStartedVideoCaptureMode);
}
else
{
Debug.LogError("Failed to create VideoCapture Instance!");
}
}
開始後,開始錄製
void OnStartedVideoCaptureMode(VideoCapture.VideoCaptureResult result)
{
if (result.success)
{
string filename = string.Format("MyVideo_{0}.mp4", Time.time);
string filepath = System.IO.Path.Combine(Application.persistentDataPath, filename);
m_VideoCapture.StartRecordingAsync(filepath, OnStartedRecordingVideo);
}
}
錄製開始後,您可以更新 UI 或行為以啟用停止。 在這裡您只需記錄即可。
void OnStartedRecordingVideo(VideoCapture.VideoCaptureResult result)
{
Debug.Log("Started Recording Video!");
// We will stop the video from recording via other input such as a timer or a tap, etc.
}
例如,稍後,您需要使用計時器或使用者輸入來停止錄製。
// The user has indicated to stop recording
void StopRecordingVideo()
{
m_VideoCapture.StopRecordingAsync(OnStoppedRecordingVideo);
}
錄製停止後,停止視訊模式並清理您的資源。
void OnStoppedRecordingVideo(VideoCapture.VideoCaptureResult result)
{
Debug.Log("Stopped Recording Video!");
m_VideoCapture.StopVideoModeAsync(OnStoppedVideoCaptureMode);
}
void OnStoppedVideoCaptureMode(VideoCapture.VideoCaptureResult result)
{
m_VideoCapture.Dispose();
m_VideoCapture = null;
}
疑難排解
- 沒有可用的解決方案
- 確保您的專案中指定 了 WebCam 功能。
下一個開發檢查點
如果您遵循我們所列出的 Unity 開發檢查點旅程,您正在探索 Mixed Reality 平臺功能和 API。 從這裡,您可以繼續下一個主題:
或直接跳至在裝置或模擬器上部署應用程式:
您隨時可以返回 Unity 開發檢查點 。