- Home /
Question by
hellojbb1234 · Jan 19, 2017 at 10:02 AM ·
c#audiosine-wave
How do I add to channels or sine waves?
I want to make it so I can play either beats or chords at the same time as the normal tones. However anytime I try it always ends up sounding irritating. Here is the music player script
using UnityEngine;
using System; // Needed for Math
public class Sinus : MonoBehaviour
{
// un-optimized version
public double frequency = 440;//This detects key and
public double gain = 0.05;
private double increment;
private double phase;
public PlayerController moveFor;
private System.Random RandomNumber = new System.Random();
private double sampling_frequency = 48000;
void Start()
{
moveFor = GameObject.FindObjectOfType<PlayerController>();
}
void OnAudioFilterRead(float[] data, int channels)
{
// update increment in case frequency has changed
increment = frequency * 2 * Math.PI / sampling_frequency;
for (var i = 0; i < data.Length; i = i + channels)
{
phase = phase + increment;
// this is where we copy audio data to make them “available” to Unity
data[i] = (float)(gain * Math.Sin(phase));
// if we have stereo, we copy the mono data to each channel
if (channels == 2) data[i + 1] = data[i];
if (phase > 2 * Math.PI) phase = 0;
}
}
}
Comment
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Envelope in OnAudioFilterRead method 1 Answer
Multiple Cars not working 1 Answer
Audio Trigger 3 Answers
Every few seconds, play an audio clip 3 Answers