1515 */
1616#include < android/log.h>
1717#include " AudioEngine.h"
18+ #include < thread>
19+ #include < mutex>
1820
1921aaudio_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+
2941AudioEngine::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+
7295void AudioEngine::setToneOn (bool isToneOn) {
7396 oscillator_->setWaveOn (isToneOn);
7497}
0 commit comments