Skip to content

Commit dffb8a8

Browse files
mikimiki-totefu
authored andcommitted
audio: improve device change on Android
1 parent 38956a2 commit dffb8a8

File tree

4 files changed

+22
-0
lines changed

4 files changed

+22
-0
lines changed

bruig/flutterui/bruig/lib/models/audio.dart

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,8 @@ class AudioModel extends ChangeNotifier {
192192
}
193193
androidFoundPlaybackDevices =
194194
androidEarpieceDeviceID != "" && androidSpeakerDeviceID != "";
195+
debugPrint(
196+
"FoundPlaybackDevices $androidFoundPlaybackDevices earpiece $androidEarpieceDeviceID speaker $androidSpeakerDeviceID");
195197
}
196198

197199
notifyListeners();

internal/audio/audio.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ type audioContext interface {
8585
// playbackDevice lists the calls needed for a playback device (malgo or sim).
8686
type playbackDevice interface {
8787
Start() error
88+
Stop() error
8889
Uninit()
8990
}
9091

internal/audio/malgoaudio.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,8 @@ func (mpc *malgoContext) initPlayback(deviceID DeviceID, cb dataProc) (playbackD
176176
deviceConfig.AAudio.ContentType = malgo.AAudioContentTypeSpeech
177177
deviceConfig.AAudio.InputPreset = malgo.AAudioInputPresetVoiceCommunication
178178
deviceConfig.AAudio.AllowedCapturePolicy = malgo.AAudioAllowCapturePolicyBySystem
179+
deviceConfig.AAudio.NoAutoStartAfterReroute = 1
180+
deviceConfig.AAudio.EnableCompatibilityWorkarounds = 0
179181

180182
playbackCallbacks := malgo.DeviceCallbacks{
181183
Data: malgo.DataProc(cb),

internal/audio/streams.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"errors"
66
"fmt"
77
"math"
8+
"runtime"
89
"sync"
910
"time"
1011

@@ -858,6 +859,10 @@ func (ps *PlaybackStream) playbackLoopWithDevice(ctx context.Context, devID Devi
858859
time.Sleep(time.Millisecond * periodSizeMS)
859860
}
860861

862+
if err := device.Stop(); err != nil {
863+
ps.log.Errorf("Playback device %q stop() call errored: %v", devID, err)
864+
}
865+
861866
device.Uninit()
862867

863868
if addDebugTrace {
@@ -905,6 +910,18 @@ func (ps *PlaybackStream) playbackLoop(ctx context.Context) error {
905910
}
906911
case <-ctx.Done():
907912
}
913+
914+
if runtime.GOOS == "android" {
915+
// Without this extra delay on android, AAudio
916+
// sometimes reuses the old device, causes
917+
// a re-route in the audio playback stack and
918+
// ends up locking up the playback loop.
919+
select {
920+
case <-time.After(time.Millisecond * 500):
921+
ps.log.Debugf("Delayed changed to new device ID %q", devID)
922+
case <-ctx.Done():
923+
}
924+
}
908925
}
909926
}
910927
return ctx.Err()

0 commit comments

Comments
 (0)