• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  * Sinewave oscillator.
21  */
22 public class SineOscillator extends SawOscillator {
23     // Factorial constants.
24     private static final float IF3 = 1.0f / (2 * 3);
25     private static final float IF5 = IF3 / (4 * 5);
26     private static final float IF7 = IF5 / (6 * 7);
27     private static final float IF9 = IF7 / (8 * 9);
28     private static final float IF11 = IF9 / (10 * 11);
29 
30     /**
31      * Calculate sine using Taylor expansion. Do not use values outside the range.
32      *
33      * @param currentPhase in the range of -1.0 to +1.0 for one cycle
34      */
fastSin(float currentPhase)35     public static float fastSin(float currentPhase) {
36 
37         /* Wrap phase back into region where results are more accurate. */
38         float yp = (currentPhase > 0.5f) ? 1.0f - currentPhase
39                 : ((currentPhase < (-0.5f)) ? (-1.0f) - currentPhase : currentPhase);
40 
41         float x = (float) (yp * Math.PI);
42         float x2 = (x * x);
43         /* Taylor expansion out to x**11/11! factored into multiply-adds */
44         return x * (x2 * (x2 * (x2 * (x2 * ((x2 * (-IF11)) + IF9) - IF7) + IF5) - IF3) + 1);
45     }
46 
47     @Override
render()48     public float render() {
49         // Convert raw sawtooth to sine.
50         float phase = incrementWrapPhase();
51         return fastSin(phase) * getAmplitude();
52     }
53 
54 }
55