1 /* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.example.android.common.midi.synth; 18 19 public class SawOscillator extends SynthUnit { 20 private float mPhase = 0.0f; 21 private float mPhaseIncrement = 0.01f; 22 private float mFrequency = 0.0f; 23 private float mFrequencyScaler = 1.0f; 24 private float mAmplitude = 1.0f; 25 setPitch(float pitch)26 public void setPitch(float pitch) { 27 float freq = (float) pitchToFrequency(pitch); 28 setFrequency(freq); 29 } 30 setFrequency(float frequency)31 public void setFrequency(float frequency) { 32 mFrequency = frequency; 33 updatePhaseIncrement(); 34 } 35 updatePhaseIncrement()36 private void updatePhaseIncrement() { 37 mPhaseIncrement = 2.0f * mFrequency * mFrequencyScaler / 48000.0f; 38 } 39 setAmplitude(float amplitude)40 public void setAmplitude(float amplitude) { 41 mAmplitude = amplitude; 42 } 43 getAmplitude()44 public float getAmplitude() { 45 return mAmplitude; 46 } 47 getFrequencyScaler()48 public float getFrequencyScaler() { 49 return mFrequencyScaler; 50 } 51 setFrequencyScaler(float frequencyScaler)52 public void setFrequencyScaler(float frequencyScaler) { 53 mFrequencyScaler = frequencyScaler; 54 updatePhaseIncrement(); 55 } 56 incrementWrapPhase()57 float incrementWrapPhase() { 58 mPhase += mPhaseIncrement; 59 while (mPhase > 1.0) { 60 mPhase -= 2.0; 61 } 62 while (mPhase < -1.0) { 63 mPhase += 2.0; 64 } 65 return mPhase; 66 } 67 68 @Override render()69 public float render() { 70 return incrementWrapPhase() * mAmplitude; 71 } 72 73 } 74