I’m trying to attach a sinusoid script to the main camera to have it play a sound after the game has started. Here’s my script:
using UnityEngine;
using System;
public class Sinus : MonoBehaviour
{
public double frequency = 440;
public double gain = 0.5;
private double increment;
private double phase;
private double sampling_frequency = 48000;
void OnAudioFilterRead(float[] data, int channels)
{
increment = frequency * 2 * Math.PI / sampling_frequency;
for (var i = 0; i < data.Length; i = i + channels) {
phase = phase + increment;
data[i] = (float)(gain*Math.Sin(phase));
if(channels == 2){
data[i + 1] = data[i];
if(phase > 2*Math.PI){
phase = 0;
}
}
}
}
public void setFrequency(double frequency){
this.frequency = frequency;
}
public double getFrequency(){
return frequency;
}
}
Here’s how I’m attaching it:
using UnityEngine;
using System.Collections;
public class Watcher : MonoBehaviour {
ArrayList spots;
Sinus testSinus;
// Use this for initialization
void Start () {
//spots = new ArrayList[Spot];
testSinus = this.gameObject.AddComponent<Sinus>();
}
}
If I drag the Sinus script onto the MainCamera and then run the game, it plays fine. If I drag the Watcher script onto the MainCamera, I see the Sinus script get created, but it doesn’t play until I uncheck and then recheck the camera’s AudioListener in the Inspector window. What am I missing?