Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // based on YouTube tutorial by Dano Kablamo:
- // https://youtu.be/GqHFGMy_51c
- // https://www.reddit.com/r/Unity3D/comments/5lwwpn/i_made_this_tutorial_showing_you_how_to_get_nes/
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Oscillator : MonoBehaviour {
- public double frequency = 440.0; // freq in hz
- private double increment; //
- private double phase; // location on wave
- private double sampling_frequency = 48000.0; // 48k
- // volume/power of audio
- public float gain;
- public float volume = 0.1f;
- public float[] frequencies;
- public int thisFreq;
- void Start() {
- frequencies = new float[8];
- frequencies[0] = 440;
- frequencies[1] = 494;
- frequencies[2] = 554;
- frequencies[3] = 587;
- frequencies[4] = 659;
- frequencies[5] = 740;
- frequencies[6] = 831;
- frequencies[7] = 880;
- }
- void Update() {
- if (Input.GetKeyDown(KeyCode.Space)) {
- gain = volume;
- frequency = frequencies[thisFreq];
- thisFreq++;
- thisFreq = thisFreq % frequencies.Length;
- }
- if (Input.GetKeyUp(KeyCode.Space)) {
- gain = 0;
- }
- }
- private void OnAudioFilterRead(float[] data, int channels) {
- increment = frequency * 2.0 * Mathf.PI / sampling_frequency;
- for (int i = 0; i < data.Length; i += channels) {
- phase += increment;
- data[i] = 0;
- /*
- //Sin
- data[i] += (float)(gain * Mathf.Sin((float)(phase)));
- /**/
- //Square
- if (gain * Mathf.Sin((float)phase) >= 0 * gain) {
- data[i] += (float)gain * 0.6f;
- } else {
- data[i] += (float)gain * -0.6f;
- }
- /**/
- /*
- // Triangle
- data[i] += (float)(gain * (double)Mathf.PingPong((float)phase, 1.0f));
- /**/
- //data[i] = data[i] / 3;
- if (channels == 2) {
- data[i + 1] = data[i];
- }
- if (phase > Mathf.PI * 2) {
- phase = 0.0;
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment