void PlayTone() { for (int i = 0; i < sines.Length; i++) { SineWaveSource swc = sines[i]; swc.phase = 0; swc.phaseOffset = i * TWO_PI / sines.Length; swc.duration = swc.envelope[swc.envelope.length - 1].time - swc.envelope[0].time; swc.started = false; sines[i] = swc; } if (!_source.isPlaying) { _source.Play(); } }
void OnAudioFilterRead(float[] data, int channels) { double now = AudioSettings.dspTime; double dspTimeIncrement = 1 / ((double)_sampleRate * envelopeTimeScale); int expiredCount = 0; for (int s = 0, sEnd = sines.Length; s < sEnd; s++) { SineWaveSource swc = sines[s]; if (!swc.started) { swc.startTime = now; swc.started = true; } double age = (now - swc.startTime) / envelopeTimeScale; float increment = frequencyMultiplier * swc.frequency * TWO_PI / _sampleRate; for (int i = 0, iEnd = data.Length; i < iEnd; i += channels) { swc.phase += increment; float envelope = Mathf.Max(swc.envelope.Evaluate((float)age), 0); float value = (envelope * swc.gain * Mathf.Sin(swc.phase + swc.phaseOffset)); age += dspTimeIncrement; data[i] += value; if (channels == 2) { data[i + 1] += value; } } sines[s] = swc; if (!swc.loop && age > swc.duration) { expiredCount++; } } }