当前位置:   article > 正文

Hololens 2拍摄视频并同步记录眼镜参数的C#脚本_hololens2全局录像

hololens2全局录像

添加一个button控件,当用户点击该控件时,HL2开始拍摄场景,同时记录眼镜传感器相关参数并保存至眼镜中软件路径下的txt中。我这边是保存的相机的位置、三个轴的向量以及欧拉角

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;
using System;

#if WINDOWS_UWP
using Windows.Storage;
using Windows.Foundation;
using Windows.System;
using System.Collections.Generic;
using System;
using System.IO;
#endif

#if UNITY_EDITOR || UNITY_WSA

#endif

//https://docs.unity3d.com/ScriptReference/Windows.WebCam.PhotoCapture.html
public class HoloPhotoVideoCapture : MonoBehaviour {
    String Poslist = String.Empty;
    String Uplist = String.Empty;
    String Forwardlist = String.Empty;
    String Rightlist = String.Empty;
    String Anglelist = String.Empty;
    StreamWriter Poswriter;
    StreamWriter Upwriter;
    StreamWriter Forwardwriter;
    StreamWriter Rightwriter;
    StreamWriter Anglewriter;

    public Camera MyCamera;

    void Start () {
        MyCamera = GameObject.Find("Main Camera").GetComponent<Camera>();
    }

    // Update is called once per frame
    void FixedUpdate () {
	   Vector3 Cam_Pos = MyCamera.transform.position;
	   String[] strPos = { Cam_Pos[0].ToString() + " ", Cam_Pos[1].ToString() + " ", Cam_Pos[2].ToString() + "\n"};
	   Vector3 Cam_up = NormalVector(MyCamera.transform.up);
	   String[] strUp = { Cam_up[0].ToString() + " ", Cam_up[1].ToString() + " ", Cam_up[2].ToString() + "\n" };
	   Vector3 Cam_forward = NormalVector(MyCamera.transform.forward);
	   String[] strForward = { Cam_forward[0].ToString() + " ", Cam_forward[1].ToString() + " ", Cam_forward[2].ToString() + "\n" };
	   Vector3 Cam_right = NormalVector(MyCamera.transform.right);
	   String[] strRight = { Cam_right[0].ToString() + " ", Cam_right[1].ToString() + " ", Cam_right[2].ToString() + "\n" };
	   Vector3 Cam_Angle = NormalVector(MyCamera.transform.localEulerAngles);
	   String[] strAngle = { Cam_Angle[0].ToString() + " ", Cam_Angle[1].ToString() + " ", Cam_Angle[2].ToString() + "\n" };
	
	   Poslist = string.Concat(Poslist, strPos[0], strPos[1], strPos[2]);
	   Uplist = string.Concat(Uplist, strUp[0], strUp[1], strUp[2]);
	   Forwardlist = string.Concat(Forwardlist, strForward[0], strForward[1], strForward[2]);
	   Rightlist = string.Concat(Rightlist, strRight[0], strRight[1], strRight[2]);
	   Anglelist = string.Concat(Anglelist, strAngle[0], strAngle[1], strAngle[2]);
	   //print(Uplist);      
	}
	
    Vector3 NormalVector(Vector3 vec)
    {

        float sum = Mathf.Sqrt(vec.x * vec.x + vec.y * vec.y + vec.z * vec.z);

        float Nor_X = vec.x / sum;
        float Nor_Y = vec.y / sum;
        float Nor_Z = vec.z / sum;

        Vector3 nor = new Vector3(Nor_X, Nor_Y, Nor_Z);

        return nor;
    }
    public void SavePhoto()
    {
        //Texture2D tex = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, true);
        //tex.Apply();
        DateTime dateTime = DateTime.Now.ToLocalTime();
        string strNowTime = string.Format("{0:D}{1:D}{2:D}", dateTime.Hour, dateTime.Minute, dateTime.Second);

        SavenPic(targetTexture, strNowTime);
    }
    public void SavenPic(Texture2D tex, string filename)
    {
        try
        {
            string path = Application.persistentDataPath + "/" + filename+ ".jpg";

            File.WriteAllBytes(path, tex.EncodeToJPG());

            print("保存成功!" + path);

        }
        catch (System.Exception e)
        {
            print("保存失败!" + e.Message);

        }

    }

    private IEnumerator LoadPic(string picname)
    {
        string path = Application.persistentDataPath + "/" + picname + ".jpg" ;
        if (File.Exists(path))
        {
            WWW www = new WWW("file:///" + path);
            yield return www;

            //获取Texture
            Texture2D dynaPic = www.texture;
            print("读取成功");
        }
        else
        {
            print("图片不存在!");
        }
    }

    #region 录像
#if UNITY_EDITOR || UNITY_WSA

    UnityEngine.Windows.WebCam.VideoCapture m_VideoCapture = null;
 
    string videofilename;
    string videofilepath;
    String TimeStr;

    public void StopVideo()
    {
        if (isRecording)
        {
            isRecording = false;

            Poswriter.WriteLine(Poslist);
            Poswriter.Close();
            Upwriter.WriteLine(Uplist);
            Upwriter.Close();
            Forwardwriter.WriteLine(Forwardlist);
            Forwardwriter.Close();
            Rightwriter.WriteLine(Rightlist);
            Rightwriter.Close();
            Anglewriter.WriteLine(Anglelist);
            Anglewriter.Close();
            print("停止录像...");

            if(Application.platform==RuntimePlatform.WSAPlayerX86|| Application.platform == RuntimePlatform.WSAPlayerARM)
            m_VideoCapture.StopRecordingAsync(OnStoppedRecordingVideo);   
        }

#if !UNITY_EDITOR && UNITY_WINRT_10_0
        string _filename = "video.mp4";
        var cameraRollFolder = Windows.Storage.KnownFolders.CameraRoll.Path;            
        File.Move(videofilepath, Path.Combine(cameraRollFolder, _filename));
#endif
    }
    public void TakeVideo()
    {
#if UNITY_EDITOR || UNITY_WSA
        if (!isRecording)
        {
            DateTime dateTime = DateTime.Now.ToLocalTime();
            TimeStr = string.Format("{0:D}{1:D}{2:D}", dateTime.Hour, dateTime.Minute, dateTime.Second);
            string Postxt = Path.Combine(Application.persistentDataPath, "Position_"+ TimeStr + ".txt");
            string Uptxt = Path.Combine(Application.persistentDataPath, "Updir_" + TimeStr + ".txt");
            string Forwardtxt = Path.Combine(Application.persistentDataPath, "Forwarddir_" + TimeStr + ".txt");
            string Righttxt = Path.Combine(Application.persistentDataPath, "Rightdir_" + TimeStr + ".txt");
            string Angletxt = Path.Combine(Application.persistentDataPath, "Angle_" + TimeStr + ".txt");
            FileInfo fi = new FileInfo(Postxt);
            FileInfo fi1 = new FileInfo(Uptxt);
            FileInfo fi2 = new FileInfo(Forwardtxt);
            FileInfo fi3 = new FileInfo(Righttxt);
            FileInfo fi4 = new FileInfo(Angletxt);
            Poswriter = fi.CreateText();
            Upwriter = fi1.CreateText();
            Forwardwriter = fi2.CreateText();
            Rightwriter = fi3.CreateText();
            Anglewriter = fi4.CreateText();

            isRecording = true;
            print("开始录像...");
            if (Application.platform == RuntimePlatform.WSAPlayerX86 || Application.platform == RuntimePlatform.WSAPlayerARM)
                UnityEngine.Windows.WebCam.VideoCapture.CreateAsync(ShowHologram, StartVideoCapture);
        }
#else

#endif
    }
    void StartVideoCapture(UnityEngine.Windows.WebCam.VideoCapture videoCapture)
    {

        if (videoCapture != null)
        {

            m_VideoCapture = videoCapture;
            Debug.Log("Created VideoCapture Instance!");

            Resolution cameraResolution = UnityEngine.Windows.WebCam.VideoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();
            float cameraFramerate = UnityEngine.Windows.WebCam.VideoCapture.GetSupportedFrameRatesForResolution(cameraResolution).OrderByDescending((fps) => fps).First();
            Debug.Log("刷新率:" + cameraFramerate);

            UnityEngine.Windows.WebCam.CameraParameters cameraParameters = new UnityEngine.Windows.WebCam.CameraParameters();
            cameraParameters.hologramOpacity = 0.9f;
            cameraParameters.frameRate = cameraFramerate;
            cameraParameters.cameraResolutionWidth = cameraResolution.width;
            cameraParameters.cameraResolutionHeight = cameraResolution.height;
            cameraParameters.pixelFormat = UnityEngine.Windows.WebCam.CapturePixelFormat.BGRA32;

            m_VideoCapture.StartVideoModeAsync(cameraParameters,
                UnityEngine.Windows.WebCam.VideoCapture.AudioState.ApplicationAndMicAudio,
                OnStartedVideoCaptureMode);
        }
        else
        {
            Debug.LogError("Failed to create VideoCapture Instance!");
        }
    }

    void OnStartedVideoCaptureMode(UnityEngine.Windows.WebCam.VideoCapture.VideoCaptureResult result)
    {
        Debug.Log("开始录像模式!");
        //获取系统时间方法1
        //string timeStamp = Time.time.ToString().Replace(".", "").Replace(":", "");
        //string filename = string.Format("TestVideo_{0}.mp4", timeStamp);
        //方法2
        DateTime dateTime = DateTime.Now.ToLocalTime();
        videofilename = "Video" + TimeStr + ".mp4";
        //string filename = "TestVideo.mp4";

        videofilepath = Path.Combine(Application.persistentDataPath, videofilename );
        videofilepath = videofilepath.Replace("/", @"\");
        m_VideoCapture.StartRecordingAsync(videofilepath, OnStartedRecordingVideo);
        Debug.Log("videopath:" + videofilepath);
    }

    void OnStoppedVideoCaptureMode(UnityEngine.Windows.WebCam.VideoCapture.VideoCaptureResult result)
    {
        m_VideoCapture.Dispose();
        m_VideoCapture = null;
        Debug.Log("停止录像模式!");
    }

    void OnStartedRecordingVideo(UnityEngine.Windows.WebCam.VideoCapture.VideoCaptureResult result)
    {
        Debug.Log("开始录像!");
    }

    void OnStoppedRecordingVideo(UnityEngine.Windows.WebCam.VideoCapture.VideoCaptureResult result)
    {
        Debug.Log("停止录像!");
        m_VideoCapture.StopVideoModeAsync(OnStoppedVideoCaptureMode);
    }
#endif

 #endregion
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258

记录:

  1. 获取当前时间作为文件命名:
DateTime dateTime = DateTime.Now.ToLocalTime();
string strNowTime = string.Format("{0:D}{1:D}{2:D}", dateTime.Hour, dateTime.Minute, dateTime.Second);
  • 1
  • 2
  1. 将string数据不断地添加到数组中
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;
using System;

public class Test : MonoBehaviour
{
    void Start()
    {
        string str1 = "Hello Hole  dsuhf sdfhuidff  fhdifh w";
        string str2 = "World";
        string newStr;
        List<String> myList = new List<String>();
        String stringfromlist = String.Empty;

        newStr = string.Concat(str1, str2);
        Debug.Log("Concat方法:" + newStr);
        newStr = string.Join("^^", str1, str2);
        Debug.Log("Join方法:" + newStr);
        newStr = str1 + str2;
        Debug.Log("连接运算符:" + newStr);
        myList.Add(str1);
        myList.Add(str2);
        for (int i = 0; i < myList.Count; i++)
        {
            stringfromlist = stringfromlist + myList[i] + " ";

        }
        Debug.Log("List<String>方法:" + stringfromlist);

    }

    private void Update()
    {
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/125777
推荐阅读
相关标签
  

闽ICP备14008679号