1 /* 2 * Copyright 2018 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 18 #ifndef SHARED_OSCILLATOR_H 19 #define SHARED_OSCILLATOR_H 20 21 22 #include <cstdint> 23 #include <atomic> 24 #include <math.h> 25 #include <memory> 26 #include "IRenderableAudio.h" 27 28 constexpr double kDefaultFrequency = 440.0; 29 constexpr int32_t kDefaultSampleRate = 48000; 30 constexpr double kPi = M_PI; 31 constexpr double kTwoPi = kPi * 2; 32 33 class Oscillator : public IRenderableAudio { 34 35 public: 36 37 ~Oscillator() = default; 38 setWaveOn(bool isWaveOn)39 void setWaveOn(bool isWaveOn) { 40 mIsWaveOn.store(isWaveOn); 41 }; 42 setSampleRate(int32_t sampleRate)43 void setSampleRate(int32_t sampleRate) { 44 mSampleRate = sampleRate; 45 updatePhaseIncrement(); 46 }; 47 setFrequency(double frequency)48 void setFrequency(double frequency) { 49 mFrequency = frequency; 50 updatePhaseIncrement(); 51 }; 52 setAmplitude(float amplitude)53 inline void setAmplitude(float amplitude) { 54 mAmplitude = amplitude; 55 }; 56 57 // From IRenderableAudio renderAudio(float * audioData,int32_t numFrames)58 void renderAudio(float *audioData, int32_t numFrames) override { 59 60 if (mIsWaveOn){ 61 for (int i = 0; i < numFrames; ++i) { 62 63 // Sine wave (sinf) 64 //data[i*kChannelCount] = sinf(mPhase) * mAmplitude; 65 66 // Square wave 67 if (mPhase <= kPi){ 68 audioData[i] = -mAmplitude; 69 } else { 70 audioData[i] = mAmplitude; 71 } 72 73 mPhase += mPhaseIncrement; 74 if (mPhase > kTwoPi) mPhase -= kTwoPi; 75 } 76 } else { 77 memset(audioData, 0, sizeof(float) * numFrames); 78 } 79 }; 80 81 private: 82 std::atomic<bool> mIsWaveOn { false }; 83 float mPhase = 0.0; 84 std::atomic<float> mAmplitude { 0 }; 85 std::atomic<double> mPhaseIncrement { 0.0 }; 86 double mFrequency = kDefaultFrequency; 87 int32_t mSampleRate = kDefaultSampleRate; 88 updatePhaseIncrement()89 void updatePhaseIncrement(){ 90 mPhaseIncrement.store((kTwoPi * mFrequency) / static_cast<double>(mSampleRate)); 91 }; 92 }; 93 94 #endif //SHARED_OSCILLATOR_H 95