Hi,
My Unity Version is 2020.3.40f
I am using the ROS2 audio_common package to send AudioData to Unity.
There I continuously receive a byte Array out of which I want to generate an audio stream inside Unity.
Unfortunately I am a complete newby in sound generation and just can’t make it work.
My code looks like this atm:
using UnityEngine;
using System;
namespace RosSharp.RosBridgeClient
{
public class AudioSubscriber : UnitySubscriber<MessageTypes.AudioCommon.AudioData>
{
public int buffer = 320;
public byte channels = 1;
// Sampling rate [Hz]
public int sample_rate = 16000;
// Audio format (e.g. S16LE)
public string sample_format = "S16LE";
// Amount of audio data per second [bits/s]
public uint bitrate = 128;
// Audio coding format (e.g. WAVE, MP3)
public string coding_format = "WAVE";
private float[] data;
private bool audioReceived;
private bool clipStarted;
AudioSource source;
AudioClip.PCMReaderCallback callback;
AudioClip clip;
protected override void Start()
{
audioReceived = false;
clipStarted = false;
source = GetComponent<AudioSource>();
clip = AudioClip.Create("stream", 320, channels, sample_rate, true, callback);
source.clip = clip;
base.Start();
}
private void Update()
{
if(audioReceived && !clipStarted)
{
source.Play();
clipStarted = true;
}
}
protected override void ReceiveMessage(MessageTypes.AudioCommon.AudioData message)
{
//float[] samples = new float[message.data.Length / 4];
//Buffer.BlockCopy(message.data, 0, samples, 0, message.data.Length);
float[] floatArr = transformByteToFloatInRange(message.data);
callback = delegate (float[] data)
{
data = floatArr;
};
//clip.SetData(data, message.data.Length);
audioReceived = true;
}
// Trying to convert the byte between 0 and 255 to float between -1 and 1
float[] transformByteToFloatInRange(byte[] data)
{
float[] floatArr = new float[data.Length];
for(int i = 0; i < data.Length; i++)
{
floatArr[i] = (data[i] / 127.5f) - 1;
}
return floatArr;
}
}
}
Can anyone maybe see what I am doing wrong and what needs to be changed?
Thanks in advance.