Skip to content

Instantly share code, notes, and snippets.

@hecomi
Created April 21, 2022 15:47
Show Gist options
  • Save hecomi/9414415d62129b81ed99e9a7b32e0f2c to your computer and use it in GitHub Desktop.
Save hecomi/9414415d62129b81ed99e9a7b32e0f2c to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using UnityEngine;
public class VoiceSpeaker : MonoBehaviour
{
private List<float> _buffer = new List<float>();
private object _lockObject = new object();
private AudioSource _source;
private AudioClip _speakerClip;
private const int SampleRate = 16000;
private const int RecordingTime = 1;
void Start()
{
_source = GetComponent<AudioSource>();
_speakerClip = AudioClip.Create("Speaker", SampleRate * RecordingTime, 1, SampleRate, true, OnAudioRead);
_source.clip = _speakerClip;
_source.loop = true;
_source.Play();
}
public void RecvData(List<float> data)
{
lock (_lockObject)
{
_buffer.AddRange(data);
}
}
void OnAudioRead(float[] data)
{
System.Array.Clear(data, 0, data.Length);
if (_buffer == null) return;
lock (_lockObject)
{
if (_buffer.Count < data.Length) return;
for (int i = 0; i < data.Length; ++i)
{
data[i] = _buffer[i];
}
_buffer.RemoveRange(0, data.Length);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment