Online client code execution
Hi guys, I am trying to implement a simple voice chat. I have 2 player, an host and a client, I want that both could hear the other's voice. I have write a very simple script, but I have a very weird problem and I cannot figure out what's wrong. All the methods are correctly called as I expected, but the audio is playing only on server.
Let's me explain better: I have a host and a client, when I mute the host I can hear my voice through the server windows, but when I mute the server I hear nothing. The method for receiving the voice is correctly called, but nothing is played. I have tried to breakpoint it, and all the variable seems to have correct value.
It is the same code on both client and server, but it only works on server. Does someone have an idea of where could be the problem?
const int FREQUENCY = 20000, secs = 4;
AudioClip mic;
int micLastPos = 0;
float[] cleaner = null;
// Use this for initialization
void Start () {
// Get microphone.
mic = Microphone.Start(null, true, secs, FREQUENCY);
// Create audio clip.
GetComponent<AudioSource>().clip = AudioClip.Create("test", secs * FREQUENCY, mic.channels, FREQUENCY, false);
}
// Update is called once per frame
void Update () {
int pos;
if(isLocalPlayer){
if((pos = Microphone.GetPosition(null)) > 0){
if(micLastPos > pos)
micLastPos = 0;
if(pos - micLastPos > 0){
// Allocate the space for the sample.
float[] sample = new float[(pos - micLastPos) * mic.channels];
// Get the data from microphone.
mic.GetData(sample, micLastPos);
// Send the data.
if(isServer)
RpcSend(sample, micLastPos);
else
CmdSend(sample, micLastPos);
micLastPos = pos;
}
}
}
}
[Command(channel=0)]
void CmdSend(float[] audioData, int position){
if(!isLocalPlayer) ReceiveAudio(audioData, position);
}
[ClientRpc]
void RpcSend(float[] audioData, int position){
if(!isLocalPlayer) ReceiveAudio(audioData, position);
}
void ReceiveAudio(float[] audioData, int position){
Debug.Log("Receiving audio...");
AudioSource audio = GetComponent<AudioSource>();
if(cleaner == null) cleaner = new float[secs * FREQUENCY];
if(position == 0)
audio.clip.SetData(cleaner, 0);
// Put the data in the audio source.
audio.clip.SetData(audioData, position);
if(!audio.isPlaying)
audio.Play();
}
Your answer
Follow this Question
Related Questions
How to: Let players talk in real time to each other in a network multiplayer game 1 Answer
Multiplayer and microphone audio streaming 1 Answer
Recording with two microphones in Unity C# 0 Answers
Audio clip repeating infinitely in update,Audio clip repeating error 0 Answers
Getting microphone data using c# 1 Answer