Deozaan

Oscillator.cs

Jan 8th, 2017
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.84 KB | None | 0 0
  1. // based on YouTube tutorial by Dano Kablamo:
  2. // https://youtu.be/GqHFGMy_51c
  3. // https://www.reddit.com/r/Unity3D/comments/5lwwpn/i_made_this_tutorial_showing_you_how_to_get_nes/
  4.  
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using UnityEngine;
  8.  
  9. public class Oscillator : MonoBehaviour {
  10.  
  11.     public double frequency = 440.0; // freq in hz
  12.     private double increment; //
  13.     private double phase; // location on wave
  14.     private double sampling_frequency = 48000.0; // 48k
  15.  
  16.     // volume/power of audio
  17.     public float gain;
  18.     public float volume = 0.1f;
  19.  
  20.     public float[] frequencies;
  21.     public int thisFreq;
  22.  
  23.     void Start() {
  24.         frequencies = new float[8];
  25.         frequencies[0] = 440;
  26.         frequencies[1] = 494;
  27.         frequencies[2] = 554;
  28.         frequencies[3] = 587;
  29.         frequencies[4] = 659;
  30.         frequencies[5] = 740;
  31.         frequencies[6] = 831;
  32.         frequencies[7] = 880;
  33.     }
  34.  
  35.     void Update() {
  36.         if (Input.GetKeyDown(KeyCode.Space)) {
  37.             gain = volume;
  38.             frequency = frequencies[thisFreq];
  39.             thisFreq++;
  40.             thisFreq = thisFreq % frequencies.Length;
  41.         }
  42.  
  43.         if (Input.GetKeyUp(KeyCode.Space)) {
  44.             gain = 0;
  45.         }
  46.     }
  47.  
  48.     private void OnAudioFilterRead(float[] data, int channels) {
  49.         increment = frequency * 2.0 * Mathf.PI / sampling_frequency;
  50.  
  51.         for (int i = 0; i < data.Length; i += channels) {
  52.             phase += increment;
  53.             data[i] = 0;
  54.             /*
  55.             //Sin
  56.             data[i] += (float)(gain * Mathf.Sin((float)(phase)));
  57.             /**/
  58.            
  59.             //Square
  60.             if (gain * Mathf.Sin((float)phase) >= 0 * gain) {
  61.                 data[i] += (float)gain * 0.6f;
  62.             } else {
  63.                 data[i] += (float)gain * -0.6f;
  64.             }
  65.             /**/
  66.             /*
  67.             // Triangle
  68.             data[i] += (float)(gain * (double)Mathf.PingPong((float)phase, 1.0f));
  69.             /**/
  70.  
  71.             //data[i] = data[i] / 3;
  72.  
  73.             if (channels == 2) {
  74.                 data[i + 1] = data[i];
  75.             }
  76.  
  77.             if (phase > Mathf.PI * 2) {
  78.                 phase = 0.0;
  79.             }
  80.         }
  81.     }
  82. }
Add Comment
Please, Sign In to add comment