Upload files to "Classes"

This commit is contained in:
Deez committed 2026-11-26 14:41:09 -05:00
1 parent 520d582c8c
commit 35a1f0d2de
2 files changed
+158

No files matched your search

+131
View File
@@ -0,0 +1,131 @@
using GorillaTag.Audio;
using Photon.Pun;
using Photon.Realtime;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace GorillaCaptions.Classes
{
public class SpeakerHook : MonoBehaviour
{
public GTSpeaker SpeakerInstance;
public VRRig OwnerRig;
public void Start()
{
if (Managers.SynthesizerManager.instance == null)
{
Debug.LogError("<Deez's GorillaCaptions> Synthesizer manager is null");
Destroy(this);
return;
}
SpeakerInstance = gameObject.GetComponent<GTSpeaker>();
if (SpeakerInstance == null)
{
Debug.LogError("<Deez's GorillaCaptions> GameObject has no speaker");
Destroy(this);
return;
}
if (!SpeakerInstance.IsLinked)
{
Debug.LogError("<Deez's GorillaCaptions> Speaker is not linked");
Destroy(this);
return;
}
OwnerRig = GetComponentInParent<VRRig>();
}
public void Update()
{
if (DateTime.Now > voiceDataTimestamp)
{
float[] audioData = null;
lock (audioLock)
{
if (audioBuffer.Count > 0)
{
audioData = audioBuffer.ToArray();
audioBuffer.Clear();
}
}
if (audioData != null)
{
_ = ProcessAudioAsync(audioData);
}
}
}
private List<float> audioBuffer = new List<float>();
private DateTime voiceDataTimestamp = DateTime.Now;
private object audioLock = new object();
public void ProcessAudioFrame(float[] frame)
{
voiceDataTimestamp = DateTime.Now.AddSeconds(0.4);
lock (audioLock)
{
audioBuffer.AddRange(frame);
}
}
private async Task ProcessAudioAsync(float[] audioData)
{
string audioPath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.wav");
await Task.Run(() =>
{
byte[] byteData = new byte[audioData.Length * sizeof(short)];
for (int i = 0; i < audioData.Length; i++)
{
short sample = (short)(Math.Clamp(audioData[i], -1f, 1f) * short.MaxValue);
byteData[i * 2] = (byte)(sample & 0xff);
byteData[i * 2 + 1] = (byte)((sample >> 8) & 0xff);
}
WriteWavFile(audioPath, byteData, 16000);
});
string output = await Managers.SynthesizerManager.instance.SynthesizeAudio(audioPath);
await Task.Run(() =>
{
if (File.Exists(audioPath))
File.Delete(audioPath);
});
if (output != null)
Managers.BubbleManager.instance.SpawnBubble(OwnerRig, output);
}
private void WriteWavFile(string path, byte[] pcmData, int sampleRate)
{
using (var fs = new FileStream(path, FileMode.Create))
using (var bw = new BinaryWriter(fs))
{
bw.Write(Encoding.ASCII.GetBytes("RIFF"));
bw.Write(36 + pcmData.Length);
bw.Write(Encoding.ASCII.GetBytes("WAVE"));
bw.Write(Encoding.ASCII.GetBytes("fmt "));
bw.Write(16);
bw.Write((short)1);
bw.Write((short)1);
bw.Write(sampleRate);
bw.Write(sampleRate * 2);
bw.Write((short)2);
bw.Write((short)16);
bw.Write(Encoding.ASCII.GetBytes("data"));
bw.Write(pcmData.Length);
bw.Write(pcmData);
}
}
}
}