- Home /
AudioSource scales audio amplitude by 0.7071 (square root of 0.5)
When an AudioSource plays an AudioClip, it appears to scale the audio data by the square root of 0.5 (0.70710678...), i.e., a value of 1.0 becomes 0.7071, 0.5 becomes 0.3536, etc. This corresponds to a reduction in gain of 3 dB (20*log10( sqrt(1/2) / 1 ) = -3.0103); -3 dB is a common value for limiters in audio production.
For example, given a wave file with a sample rate of 48000 Hz (which matches AudioSettings.outputSampleRate on my machine) containing one second of a 1 Hz sine wave, the data returned by the AudioClip match the wave file (apart from some minor compression artifacts) but the AudioSource data are scaled. Here's a plot (the ranges are limited by the amount of data that GetData and GetOutputData can return):
This behaviour doesn't seem to be documented; can it be disabled?
For reference, here's the code I used to collect the data plotted above:
using System.IO;
using UnityEngine;
public class AudioTest : MonoBehaviour
{
public AudioSource audioSource; // Should loop, play on awake, and be 2D.
public AudioClip audioClip; // Should be the same as the clip specified in the AudioSource's parameters.
private const int SampleCount = 16384; // Should be a power of two for AudioSource.GetOutputData().
private float[] _samples;
private bool _hasSavedOutput = false;
void Awake()
{
_samples = new float[SampleCount];
}
void Start ()
{
print("Sample rate of output device is " + AudioSettings.outputSampleRate + " Hz.");
audioClip.GetData(_samples, 0);
OutputSamples("fromClip");
}
void Update ()
{
if (!_hasSavedOutput)
{
audioSource.GetOutputData(_samples, 0);
// First couple calls to GetOutputData return no data.
// Apparently this is by design (see https://issuetracker.unity3d.com/issues/audiosource-dot-getoutputdata-returns-an-empty-array-the-first-time-it-is-called).
if (!Mathf.Approximately(_samples[0], 0.0f))
{
_hasSavedOutput = true;
OutputSamples("fromSource");
}
}
}
void OutputSamples(string filename)
{
string output = string.Empty;
foreach (float value in _samples)
{
output += value + "\n";
}
StreamWriter writer = new StreamWriter("C:/TestFolder/" + filename + ".txt");
writer.Write(output);
writer.Close();
}
}
Your answer
Follow this Question
Related Questions
What does 'float[] sample' in GetOutputData represent? 2 Answers
Question Related to GetSpectrumData and GetOutputData 0 Answers
Multiple audiosources 1 Answer
Play AudioSource in editor 0 Answers