Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Diagnostics;
- using System.Linq;
- using System.Security.Cryptography.X509Certificates;
- using Unity.Collections;
- using Unity.Jobs;
- using Unity.Mathematics;
- using UnityEngine;
- using Debug = UnityEngine.Debug;
- public class micRecorder : MonoBehaviour
- {
- private AudioClip clip;
- private AudioSource audio;
- private Texture2D t2d;
- // Start is called before the first frame update
- private NativeArray<Color> colors;
- private NativeArray<float> samples;
- void Start()
- {
- audio = GetComponent<AudioSource>();
- foreach (var device in Microphone.devices) { Debug.Log("Name: " + device); }
- audio.clip = Microphone.Start("Microphone (3- Logitech G933 Gaming Headset)", true, 1, 9600);
- clip = audio.clip;
- audio.loop = true;
- Stopwatch sw = new Stopwatch();
- sw.Start();
- while (!(Microphone.GetPosition("Microphone (3- Logitech G933 Gaming Headset)") > 0)) {}
- sw.Stop();
- print(sw.ElapsedMilliseconds);
- audio.Play();
- t2d = new Texture2D(512, 256, TextureFormat.RGBAFloat, false);
- GetComponent<MeshRenderer>().material.SetTexture("_MainTex", t2d);
- colors = new NativeArray<Color>(512 * 256, Allocator.Persistent);
- samples = new NativeArray<float>(9600, Allocator.Persistent);
- }
- private void OnDisable()
- {
- colors.Dispose();
- samples.Dispose();
- }
- // Update is called once per frame
- float[] sampleBuffer = new float[9600];
- private int lastCount = 0;
- void FixedUpdate()
- {
- var ds = audio.timeSamples - lastCount;
- audio.clip.GetData(sampleBuffer, 0);
- samples.CopyFrom(sampleBuffer);
- var fillJob = new FillTextureJob {colors = colors, sampleData = samples};
- fillJob.Schedule().Complete();
- t2d.SetPixels(colors.ToArray());
- t2d.Apply();
- }
- }
- struct FillTextureJob : IJob
- {
- public NativeArray<Color> colors;
- [ReadOnly] public NativeArray<float> sampleData;
- public void Execute()
- {
- int samplestep = 9600 / 512;
- for (int x = 0; x < 512; x++)
- {
- int value = (int) (sampleData[x*samplestep] * 128) + 128;
- for (int y = 0; y < 256; y++)
- {
- colors[x + y * 512] = value == y ? Color.white : Color.black;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement