- Home /
How to send audio to a specific channel?
In the article below, I found a script to take an AudioClip, get its data and send it to a new AudioClip to a specific channel.
https://thomasmountainborn.com/2016/06/10/sending-audio-directly-to-a-speaker-in-unity/
Here is the code:
public AudioClip CreateSpeakerSpecificClip(AudioClip originalClip, int amountOfChannels, int targetChannel)
{
// Create a new clip with the target amount of channels.
AudioClip clip = AudioClip.Create(originalClip.name, originalClip.samples, amountOfChannels, originalClip.frequency, false);
// Init audio arrays.
float[] audioData = new float[originalClip.samples * amountOfChannels];
float[] originalAudioData = new float[originalClip.samples * originalClip.channels];
if (!originalClip.GetData(originalAudioData, 0))
return null;
// Fill in the audio from the original clip into the target channel. Samples are interleaved by channel (L0, R0, L1, R1, etc).
int originalClipIndex = 0;
for (int i = targetChannel; i < audioData.Length; i += amountOfChannels)
{
audioData[i] = originalAudioData[originalClipIndex];
originalClipIndex += originalClip.channels;
}
if (!clip.SetData(audioData, 0))
return null;
return clip;
}
So, if I have a music (stereo) that have 2 channels, I could take this music, and copy only data from the first channel to a new AudioClip of 1 channel to play the music only on the left side.
But, when I call CreateSpeakerSpecificClip(audioClip, 1, 0), I think it should create a new AudioClip with 1 channel (2nd parameter) and target the channel at index 0 (the first and only channel, third parameter).
But, I continue to hear the music on both side. Is there anything that I don't see? Thanks
Answer by miles24 · Feb 09, 2020 at 06:47 PM
I think I found the problem. When I open Unity, my PC already needs to be in 7.1 surround or unity will consider that my PC is only stereo. I can't change my PC audio settings when Unity is opened. I need to close Unity, change my setting and reopen it. When I print these value below, Unity audio was set to 7.1 but "AudioSettings.driverCapabilities" was printing stereo and not 7.1 surround. I restarted Unity and now it's ok.
Debug.Log(AudioSettings.speakerMode);
Debug.Log(AudioSettings.driverCapabilities);
Also, don't forget to set the pan parameter of the AudioSource to center or it will play only on one side.