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 /** 20 * Band limited sawtooth oscillator. 21 * This will have very little aliasing at high frequencies. 22 */ 23 public class SawOscillatorDPW extends SawOscillator { 24 private float mZ1 = 0.0f; // delayed values 25 private float mZ2 = 0.0f; 26 private float mScaler; // frequency dependent scaler 27 private final static float VERY_LOW_FREQ = 0.0000001f; 28 29 @Override 30 public void setFrequency(float freq) { 31 /* Calculate scaling based on frequency. */ 32 freq = Math.abs(freq); 33 super.setFrequency(freq); 34 if (freq < VERY_LOW_FREQ) { 35 mScaler = (float) (0.125 * 44100 / VERY_LOW_FREQ); 36 } else { 37 mScaler = (float) (0.125 * 44100 / freq); 38 } 39 } 40 41 @Override 42 public float render() { 43 float phase = incrementWrapPhase(); 44 /* Square the raw sawtooth. */ 45 float squared = phase * phase; 46 float diffed = squared - mZ2; 47 mZ2 = mZ1; 48 mZ1 = squared; 49 return diffed * mScaler * getAmplitude(); 50 } 51 52 } 53