Search Unity

Audio Adding panning and level difference algorithms to procedurally generated audio using C# scripts

Discussion in 'Audio & Video' started by mementcode, Feb 16, 2018.

  1. mementcode

    mementcode

    Joined:
    Feb 7, 2018
    Posts:
    1
    Firstly, let me say that I am very new to UNITY and C# however I do have experience in other coding languages and MATLAB, I am having trouble converting MATLAB scripts into to C# scripts in UNITY.

    I am trying to add panning and level difference algorithms to some procedural audio (some simple sinusoids) i've created in C# for example, if my audio source is playing and is on the left hand side of the game scene then the sound should be more intense( louder) on the left audio output then it is on the right hand side and vice versus. equally if my my audio listener (character) turns left or right it again sounds more intense in whichever output (L or R) the character is facing. I am also looking to include a level difference algorithm so that when my audio listener moves closer to or further away from the audio source object it sounds quieter using the inverse square law.

    for the level difference aspect I know I have to get both the audio listener and source coordinates using,

    GameObject.Find(“[obj_name]”).transform.position and then calculate the difference between the two, and apply the inverse square law algorithm and then use the update () function to make sure it updates on every frame.

    For the panning aspect I know I need to apply a CARDIOID function so I know how intense it should be in each year depending on where the audio source is to the listener and again apply that to the coordinates of both source and listener.

    below is my code that I want to incorporate the above to which just creates a simple distorted sine-wave:


    using System.Collections;
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using System;



    public class Generic: MonoBehaviour {


    public double F = 0.0; // Frequency
    public double A = 0.0; // Amplitude
    public float Pos_Clip_Lev = 0.0f; // Postive Clipping Amplitude Level
    public float Neg_Clip_Lev = -0.0f; // Negative Clipping Amplitude Level
    private double t = 0.0; // Time Duration


    void OnAudioFilterRead(float[] data, int channels){

    for (int n = 1; n< data.Length; n = n+channels){

    t = t+(1.0/48000.0); // nth value (t)

    data [n] = (float)(A * Math.Sin (2 * Math.PI * F * t));{

    if (data [n] >= Pos_Clip_Lev) data [n] = Pos_Clip_Lev;{
    if (data [n] <= Neg_Clip_Lev) data [n] = Neg_Clip_Lev;

    }

    }

    }

    }

    }


    Hopefully the above makes sense, would be great for any help on the above!