Skip to content

Instantly share code, notes, and snippets.

@avirajkhare00
Created April 25, 2025 04:24
Show Gist options
  • Save avirajkhare00/7050133fa00b13e7a9360d3bfb3af55f to your computer and use it in GitHub Desktop.
Save avirajkhare00/7050133fa00b13e7a9360d3bfb3af55f to your computer and use it in GitHub Desktop.
using UnityEngine;
using NativeWebSocket;
using System.Collections;
public class AudioStreamer : MonoBehaviour
{
WebSocket websocket;
AudioClip micClip;
const int sampleRate = 16000;
async void Start()
{
websocket = new WebSocket("ws://yourserver:port");
websocket.OnOpen += () =>
{
Debug.Log("Connection open!");
StartCoroutine(CaptureMic());
};
websocket.OnError += (e) => Debug.Log("Error! " + e);
websocket.OnClose += (e) => Debug.Log("Closed!");
await websocket.Connect();
}
IEnumerator CaptureMic()
{
micClip = Microphone.Start(null, true, 1, sampleRate);
yield return new WaitForSeconds(1);
float[] samples = new float[micClip.samples];
micClip.GetData(samples, 0);
byte[] byteData = FloatArrayToByteArray(samples);
websocket.Send(byteData);
}
byte[] FloatArrayToByteArray(float[] floatArray)
{
byte[] byteArray = new byte[floatArray.Length * 4];
for (int i = 0; i < floatArray.Length; i++)
{
byte[] bytes = System.BitConverter.GetBytes(floatArray[i]);
bytes.CopyTo(byteArray, i * 4);
}
return byteArray;
}
private async void OnApplicationQuit()
{
await websocket.Close();
}
void Update()
{
#if !UNITY_WEBGL || UNITY_EDITOR
websocket?.DispatchMessageQueue();
#endif
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment