xref: /aosp_15_r20/external/oboe/samples/RhythmGame/src/main/cpp/audio/Player.cpp (revision 05767d913155b055644481607e6fa1e35e2fe72c)
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 #include "Player.h"
18 #include "utils/logging.h"
19 
renderAudio(float * targetData,int32_t numFrames)20 void Player::renderAudio(float *targetData, int32_t numFrames){
21 
22     const AudioProperties properties = mSource->getProperties();
23 
24     if (mIsPlaying){
25 
26         int64_t framesToRenderFromData = numFrames;
27         int64_t totalSourceFrames = mSource->getSize() / properties.channelCount;
28         const float *data = mSource->getData();
29 
30         // Check whether we're about to reach the end of the recording
31         if (!mIsLooping && mReadFrameIndex + numFrames >= totalSourceFrames){
32             framesToRenderFromData = totalSourceFrames - mReadFrameIndex;
33             mIsPlaying = false;
34         }
35 
36         for (int i = 0; i < framesToRenderFromData; ++i) {
37             for (int j = 0; j < properties.channelCount; ++j) {
38                 targetData[(i*properties.channelCount)+j] = data[(mReadFrameIndex*properties.channelCount)+j];
39             }
40 
41             // Increment and handle wraparound
42             if (++mReadFrameIndex >= totalSourceFrames) mReadFrameIndex = 0;
43         }
44 
45         if (framesToRenderFromData < numFrames){
46             // fill the rest of the buffer with silence
47             renderSilence(&targetData[framesToRenderFromData], numFrames * properties.channelCount);
48         }
49 
50     } else {
51         renderSilence(targetData, numFrames * properties.channelCount);
52     }
53 }
54 
renderSilence(float * start,int32_t numSamples)55 void Player::renderSilence(float *start, int32_t numSamples){
56     for (int i = 0; i < numSamples; ++i) {
57         start[i] = 0;
58     }
59 }
60