Skip to content
This repository was archived by the owner on Aug 16, 2023. It is now read-only.

Commit 2100725

Browse files
committed
Handle stream disconnects
1 parent f337960 commit 2100725

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

app/src/main/cpp/AudioEngine.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
*/
1616
#include <android/log.h>
1717
#include "AudioEngine.h"
18+
#include <thread>
19+
#include <mutex>
1820

1921
aaudio_data_callback_result_t dataCallback(
2022
AAudioStream *stream,
@@ -26,6 +28,16 @@ aaudio_data_callback_result_t dataCallback(
2628
return AAUDIO_CALLBACK_RESULT_CONTINUE;
2729
}
2830

31+
void errorCallback(AAudioStream *stream,
32+
void *userData,
33+
aaudio_result_t error){
34+
if (error == AAUDIO_ERROR_DISCONNECTED){
35+
std::function<void(void)> restartFunction = std::bind(&AudioEngine::restart,
36+
static_cast<AudioEngine *>(userData));
37+
new std::thread(restartFunction);
38+
}
39+
}
40+
2941
AudioEngine::AudioEngine() {
3042
oscillator_ = new Oscillator();
3143
}
@@ -37,6 +49,7 @@ bool AudioEngine::start() {
3749
AAudioStreamBuilder_setChannelCount(streamBuilder, 1);
3850
AAudioStreamBuilder_setPerformanceMode(streamBuilder, AAUDIO_PERFORMANCE_MODE_LOW_LATENCY);
3951
AAudioStreamBuilder_setDataCallback(streamBuilder, ::dataCallback, oscillator_);
52+
AAudioStreamBuilder_setErrorCallback(streamBuilder, ::errorCallback, this);
4053

4154
// Opens the stream.
4255
aaudio_result_t result = AAudioStreamBuilder_openStream(streamBuilder, &stream_);
@@ -69,6 +82,16 @@ void AudioEngine::stop() {
6982
}
7083
}
7184

85+
void AudioEngine::restart(){
86+
87+
static std::mutex restartingLock;
88+
if (restartingLock.try_lock()){
89+
stop();
90+
start();
91+
restartingLock.unlock();
92+
}
93+
}
94+
7295
void AudioEngine::setToneOn(bool isToneOn) {
7396
oscillator_->setWaveOn(isToneOn);
7497
}

app/src/main/cpp/AudioEngine.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ class AudioEngine {
2828

2929
void stop();
3030

31+
void restart();
32+
3133
void setToneOn(bool isToneOn);
3234

3335
private:

0 commit comments

Comments
 (0)