Dynamically adding sound

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?

Hi,

Have you tried adding the Sinus Component during “Awake” rather than during “Start”?

It’s just a theory but here’s something from the Unity documentation:

so, I presume that your script must be present in the scene when the AudioListener will make its Awake while you’re adding your filter in the Start of another script.
Have you tried to attach just the and run the scene to see if it works? If this is the case, you have to force the AudioListener to re-initialize itself to let the filter to be added in the DSP chain (disabling and then enabling it will do the job).

I don’t know for sure but just try and let us know how it goes !!! :wink: