Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add audio output device selector

Nathan Poulson2894b8796866
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
index b5011e5b..8011b02b 100644
--- a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
@@ -13,6 +13,7 @@ import android.os.StatFs
import android.util.Log
import com.ryanheise.audioservice.AudioServiceActivity
import com.ryanheise.just_audio.MonoController
+import com.ryanheise.just_audio.OutputDeviceController
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
@@ -25,6 +26,7 @@ class MainActivity : AudioServiceActivity() {
private var virtualizer: Virtualizer? = null
private var loudnessEnhancer: LoudnessEnhancer? = null
private var currentSessionId: Int = 0
+ private var selectedOutputDeviceId: Int? = null // user's manual override
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
@@ -75,6 +77,23 @@ class MainActivity : AudioServiceActivity() {
}
Log.d(TAG, "EQ method channel registered")
+ MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.absorb.audio_output")
+ .setMethodCallHandler { call, result ->
+ when (call.method) {
+ "getAudioOutputDevices" -> {
+ result.success(getAudioOutputDevices())
+ }
+ "setAudioOutputDevice" -> {
+ val id = call.argument<Int>("id") ?: 0
+ result.success(setAudioOutputDevice(id))
+ }
+ "resetAudioOutput" -> {
+ result.success(resetAudioOutput())
+ }
+ else -> result.notImplemented()
+ }
+ }
+
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.absorb.storage")
.setMethodCallHandler { call, result ->
when (call.method) {
@@ -206,6 +225,100 @@ class MainActivity : AudioServiceActivity() {
}
}
+ private fun getAudioOutputDevices(): List<Map<String, Any>> {
+ val am = getSystemService(Context.AUDIO_SERVICE) as AudioManager
+ val devices = am.getDevices(AudioManager.GET_DEVICES_OUTPUTS)
+ .filter { isMediaOutputDevice(it.type) }
+
+ // If user has manually selected a device, use that; otherwise fall back to priority
+ val manualId = selectedOutputDeviceId
+ val hasManualSelection = manualId != null && devices.any { it.id == manualId }
+
+ // Determine active output by priority: wired > BT A2DP > USB > speaker
+ val activeTypes: Set<Int> = when {
+ devices.any { it.type == AudioDeviceInfo.TYPE_WIRED_HEADPHONES || it.type == AudioDeviceInfo.TYPE_WIRED_HEADSET } ->
+ setOf(AudioDeviceInfo.TYPE_WIRED_HEADPHONES, AudioDeviceInfo.TYPE_WIRED_HEADSET)
+ devices.any { it.type == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP } ->
+ setOf(AudioDeviceInfo.TYPE_BLUETOOTH_A2DP)
+ devices.any { it.type == AudioDeviceInfo.TYPE_USB_DEVICE || it.type == AudioDeviceInfo.TYPE_USB_HEADSET } ->
+ setOf(AudioDeviceInfo.TYPE_USB_DEVICE, AudioDeviceInfo.TYPE_USB_HEADSET)
+ else -> setOf(AudioDeviceInfo.TYPE_BUILTIN_SPEAKER)
+ }
+
+ // Deduplicate: prefer A2DP over SCO for same product name
+ val seen = mutableSetOf<String>()
+ return devices
+ .sortedBy { if (it.type == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP) 0 else 1 }
+ .filter { device ->
+ val key = device.productName?.toString()?.takeIf { it.isNotBlank() } ?: device.id.toString()
+ seen.add(key)
+ }
+ .map { device ->
+ val typeName = getOutputTypeName(device.type)
+ val name = device.productName?.toString()?.takeIf { it.isNotBlank() }
+ ?: getOutputTypeLabel(device.type)
+ val isActive = if (hasManualSelection) device.id == manualId
+ else device.type in activeTypes
+ mapOf(
+ "id" to device.id,
+ "name" to name,
+ "typeName" to typeName,
+ "isActive" to isActive
+ )
+ }
+ }
+
+ private fun isMediaOutputDevice(type: Int): Boolean {
+ return type in listOf(
+ AudioDeviceInfo.TYPE_BUILTIN_SPEAKER,
+ AudioDeviceInfo.TYPE_WIRED_HEADPHONES,
+ AudioDeviceInfo.TYPE_WIRED_HEADSET,
+ AudioDeviceInfo.TYPE_BLUETOOTH_A2DP,
+ AudioDeviceInfo.TYPE_USB_DEVICE,
+ AudioDeviceInfo.TYPE_USB_HEADSET,
+ )
+ }
+
+ private fun getOutputTypeName(type: Int): String {
+ return when (type) {
+ AudioDeviceInfo.TYPE_BUILTIN_SPEAKER -> "speaker"
+ AudioDeviceInfo.TYPE_WIRED_HEADPHONES, AudioDeviceInfo.TYPE_WIRED_HEADSET -> "wired"
+ AudioDeviceInfo.TYPE_BLUETOOTH_A2DP -> "bluetooth"
+ AudioDeviceInfo.TYPE_USB_DEVICE, AudioDeviceInfo.TYPE_USB_HEADSET -> "usb"
+ else -> "unknown"
+ }
+ }
+
+ private fun getOutputTypeLabel(type: Int): String {
+ return when (type) {
+ AudioDeviceInfo.TYPE_BUILTIN_SPEAKER -> "This Phone"
+ AudioDeviceInfo.TYPE_WIRED_HEADPHONES -> "Wired Headphones"
+ AudioDeviceInfo.TYPE_WIRED_HEADSET -> "Wired Headset"
+ AudioDeviceInfo.TYPE_BLUETOOTH_A2DP -> "Bluetooth"
+ AudioDeviceInfo.TYPE_USB_DEVICE -> "USB Audio"
+ AudioDeviceInfo.TYPE_USB_HEADSET -> "USB Headset"
+ else -> "Audio Device"
+ }
+ }
+
+ private fun setAudioOutputDevice(deviceId: Int): Boolean {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ val am = getSystemService(Context.AUDIO_SERVICE) as AudioManager
+ val devices = am.getDevices(AudioManager.GET_DEVICES_OUTPUTS)
+ val target = devices.firstOrNull { it.id == deviceId }
+ OutputDeviceController.setPreferredOutputDevice(target)
+ selectedOutputDeviceId = deviceId
+ return true
+ }
+ return false
+ }
+
+ private fun resetAudioOutput(): Boolean {
+ OutputDeviceController.setPreferredOutputDevice(null)
+ selectedOutputDeviceId = null
+ return true
+ }
+
private fun releaseEffects() {
try { equalizer?.release() } catch (_: Exception) {}
try { bassBoost?.release() } catch (_: Exception) {}
diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift
index c30b367e..c5bb46fd 100644
--- a/ios/Runner/AppDelegate.swift
+++ b/ios/Runner/AppDelegate.swift
@@ -1,5 +1,6 @@
import Flutter
import UIKit
+import AVFoundation
@main
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
@@ -12,5 +13,105 @@ import UIKit
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
+
+ guard let controller = window?.rootViewController as? FlutterViewController else { return }
+ let channel = FlutterMethodChannel(name: "com.absorb.audio_output",
+ binaryMessenger: controller.binaryMessenger)
+ channel.setMethodCallHandler { [weak self] (call, result) in
+ switch call.method {
+ case "getAudioOutputDevices":
+ result(self?.getAudioOutputDevices() ?? [])
+ case "setAudioOutputDevice":
+ if let args = call.arguments as? [String: Any], let id = args["id"] as? Int {
+ result(self?.setAudioOutputDevice(portIndex: id) ?? false)
+ } else {
+ result(false)
+ }
+ case "resetAudioOutput":
+ result(self?.resetAudioOutput() ?? false)
+ default:
+ result(FlutterMethodNotImplemented)
+ }
+ }
+ }
+
+ private func getAudioOutputDevices() -> [[String: Any]] {
+ let session = AVAudioSession.sharedInstance()
+ let currentOutputs = session.currentRoute.outputs
+ let currentPortUIDs = Set(currentOutputs.map { $0.uid })
+
+ var devices: [[String: Any]] = []
+ var seenTypes = Set<String>()
+
+ // Add current outputs first
+ for port in currentOutputs {
+ let typeName = portTypeName(port.portType)
+ seenTypes.insert(typeName)
+ devices.append([
+ "id": port.uid.hashValue,
+ "name": port.portName,
+ "typeName": typeName,
+ "isActive": true,
+ "uid": port.uid,
+ ])
+ }
+
+ // Add available outputs that aren't current
+ for output in session.availableInputs ?? [] {
+ // availableInputs on iOS - for Bluetooth HFP, the input port maps to output too
+ }
+
+ // Always add speaker if not already current
+ if !seenTypes.contains("speaker") {
+ devices.append([
+ "id": "speaker".hashValue,
+ "name": "This iPhone",
+ "typeName": "speaker",
+ "isActive": false,
+ "uid": "speaker",
+ ])
+ }
+
+ return devices
+ }
+
+ private func portTypeName(_ portType: AVAudioSession.Port) -> String {
+ switch portType {
+ case .bluetoothA2DP, .bluetoothHFP, .bluetoothLE:
+ return "bluetooth"
+ case .headphones:
+ return "wired"
+ case .builtInSpeaker:
+ return "speaker"
+ case .builtInReceiver:
+ return "earpiece"
+ case .usbAudio:
+ return "usb"
+ default:
+ return "unknown"
+ }
+ }
+
+ private func setAudioOutputDevice(portIndex: Int) -> Bool {
+ let session = AVAudioSession.sharedInstance()
+ // If requesting speaker, override to speaker
+ if portIndex == "speaker".hashValue {
+ do {
+ try session.overrideOutputAudioPort(.speaker)
+ return true
+ } catch { return false }
+ }
+ // Otherwise, clear override to let system route to connected device
+ do {
+ try session.overrideOutputAudioPort(.none)
+ return true
+ } catch { return false }
+ }
+
+ private func resetAudioOutput() -> Bool {
+ do {
+ try AVAudioSession.sharedInstance().overrideOutputAudioPort(.none)
+ return true
+ } catch { return false }
}
}
diff --git a/lib/services/audio_output_service.dart b/lib/services/audio_output_service.dart
new file mode 100644
index 00000000..9fae5fe4
--- /dev/null
+++ b/lib/services/audio_output_service.dart
@@ -0,0 +1,68 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+class AudioOutputDevice {
+ final int id;
+ final String name;
+ final String typeName;
+ final bool isActive;
+
+ const AudioOutputDevice({
+ required this.id,
+ required this.name,
+ required this.typeName,
+ this.isActive = false,
+ });
+
+ IconData get icon {
+ switch (typeName) {
+ case 'bluetooth':
+ return Icons.bluetooth_rounded;
+ case 'wired':
+ return Icons.headphones_rounded;
+ case 'speaker':
+ return Icons.phone_android_rounded;
+ case 'earpiece':
+ return Icons.hearing_rounded;
+ case 'usb':
+ return Icons.usb_rounded;
+ default:
+ return Icons.volume_up_rounded;
+ }
+ }
+}
+
+class AudioOutputService {
+ static const _channel = MethodChannel('com.absorb.audio_output');
+
+ static Future<List<AudioOutputDevice>> getOutputDevices() async {
+ try {
+ final result = await _channel.invokeMethod('getAudioOutputDevices');
+ final list = (result as List).cast<Map>();
+ return list.map((m) => AudioOutputDevice(
+ id: m['id'] as int? ?? 0,
+ name: m['name'] as String? ?? 'Unknown',
+ typeName: m['typeName'] as String? ?? 'unknown',
+ isActive: m['isActive'] as bool? ?? false,
+ )).toList();
+ } catch (_) {
+ return [];
+ }
+ }
+
+ static Future<bool> setOutputDevice(int deviceId) async {
+ try {
+ return await _channel.invokeMethod('setAudioOutputDevice', {'id': deviceId}) == true;
+ } catch (_) {
+ return false;
+ }
+ }
+
+ static Future<bool> resetToDefault() async {
+ try {
+ return await _channel.invokeMethod('resetAudioOutput') == true;
+ } catch (_) {
+ return false;
+ }
+ }
+}
diff --git a/lib/widgets/audio_output_sheet.dart b/lib/widgets/audio_output_sheet.dart
new file mode 100644
index 00000000..35f777a2
--- /dev/null
+++ b/lib/widgets/audio_output_sheet.dart
@@ -0,0 +1,106 @@
+import 'package:flutter/material.dart';
+import '../services/audio_output_service.dart';
+
+class AudioOutputSheet extends StatefulWidget {
+ final Color accent;
+ const AudioOutputSheet({super.key, required this.accent});
+
+ @override
+ State<AudioOutputSheet> createState() => _AudioOutputSheetState();
+}
+
+class _AudioOutputSheetState extends State<AudioOutputSheet> {
+ List<AudioOutputDevice> _devices = [];
+ bool _loading = true;
+
+ @override
+ void initState() {
+ super.initState();
+ _loadDevices();
+ }
+
+ Future<void> _loadDevices() async {
+ final devices = await AudioOutputService.getOutputDevices();
+ if (mounted) setState(() { _devices = devices; _loading = false; });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ return SafeArea(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Container(
+ width: 40, height: 4,
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.24),
+ borderRadius: BorderRadius.circular(2),
+ ),
+ ),
+ const SizedBox(height: 16),
+ Text('Audio Output', style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600)),
+ const SizedBox(height: 16),
+ if (_loading)
+ const Padding(
+ padding: EdgeInsets.all(24),
+ child: CircularProgressIndicator(),
+ )
+ else if (_devices.isEmpty)
+ Padding(
+ padding: const EdgeInsets.all(24),
+ child: Text('No output devices found',
+ style: TextStyle(color: cs.onSurface.withValues(alpha: 0.5))),
+ )
+ else
+ ..._devices.map((device) => _buildDeviceTile(device, cs)),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _buildDeviceTile(AudioOutputDevice device, ColorScheme cs) {
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: GestureDetector(
+ onTap: () async {
+ await AudioOutputService.setOutputDevice(device.id);
+ await _loadDevices();
+ },
+ child: Container(
+ padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 16),
+ decoration: BoxDecoration(
+ color: device.isActive
+ ? widget.accent.withValues(alpha: 0.12)
+ : cs.onSurface.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(
+ color: device.isActive
+ ? widget.accent.withValues(alpha: 0.3)
+ : cs.onSurface.withValues(alpha: 0.08),
+ ),
+ ),
+ child: Row(
+ children: [
+ Icon(device.icon, size: 22,
+ color: device.isActive ? widget.accent : cs.onSurface.withValues(alpha: 0.6)),
+ const SizedBox(width: 14),
+ Expanded(
+ child: Text(device.name,
+ style: TextStyle(
+ fontWeight: device.isActive ? FontWeight.w600 : FontWeight.w500,
+ color: device.isActive ? widget.accent : cs.onSurface,
+ )),
+ ),
+ if (device.isActive)
+ Icon(Icons.check_rounded, size: 20, color: widget.accent),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/AudioPlayer.java b/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/AudioPlayer.java
index 1572de6d..8e828917 100644
--- a/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/AudioPlayer.java
+++ b/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/AudioPlayer.java
@@ -1,6 +1,8 @@
package com.ryanheise.just_audio;
import android.content.Context;
+import android.media.AudioDeviceInfo;
+import android.media.AudioManager;
import android.media.audiofx.AudioEffect;
import android.media.audiofx.Equalizer;
import android.media.audiofx.LoudnessEnhancer;
@@ -557,6 +559,23 @@ public class AudioPlayer implements MethodCallHandler, Player.Listener, Metadata
setAudioAttributes(call.argument("contentType"), call.argument("flags"), call.argument("usage"));
result.success(new HashMap<String, Object>());
break;
+ case "setPreferredAudioDevice":
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && player != null) {
+ Integer deviceId = call.argument("deviceId");
+ if (deviceId == null || deviceId == 0) {
+ player.setPreferredAudioDevice(null);
+ } else {
+ AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
+ AudioDeviceInfo[] devices = am.getDevices(AudioManager.GET_DEVICES_OUTPUTS);
+ AudioDeviceInfo target = null;
+ for (AudioDeviceInfo d : devices) {
+ if (d.getId() == deviceId) { target = d; break; }
+ }
+ player.setPreferredAudioDevice(target);
+ }
+ }
+ result.success(new HashMap<String, Object>());
+ break;
case "audioEffectSetEnabled":
audioEffectSetEnabled(call.argument("type"), call.argument("enabled"));
result.success(new HashMap<String, Object>());
@@ -875,6 +894,12 @@ public class AudioPlayer implements MethodCallHandler, Player.Listener, Metadata
builder.setLivePlaybackSpeedControl(livePlaybackSpeedControl);
}
player = builder.build();
+ final ExoPlayer p = player;
+ OutputDeviceController.register(device -> {
+ if (p != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ p.setPreferredAudioDevice(device);
+ }
+ });
// player.setTrackSelectionParameters(
// player.getTrackSelectionParameters()
// .buildUpon()
diff --git a/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/OutputDeviceController.java b/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/OutputDeviceController.java
new file mode 100644
index 00000000..84c1956f
--- /dev/null
+++ b/packages/just_audio/android/src/main/java/com/ryanheise/just_audio/OutputDeviceController.java
@@ -0,0 +1,25 @@
+package com.ryanheise.just_audio;
+
+import android.media.AudioDeviceInfo;
+
+/**
+ * Static bridge so external code (e.g. MainActivity) can set the preferred
+ * audio output device without directly importing AudioPlayer (which causes
+ * classpath issues with media3 types).
+ */
+public class OutputDeviceController {
+ public interface Callback {
+ void setPreferredAudioDevice(AudioDeviceInfo device);
+ }
+
+ private static volatile Callback sCallback;
+
+ public static void register(Callback callback) {
+ sCallback = callback;
+ }
+
+ public static void setPreferredOutputDevice(AudioDeviceInfo device) {
+ Callback cb = sCallback;
+ if (cb != null) cb.setPreferredAudioDevice(device);
+ }
+}