经典蓝牙-A2DP音频传输模块
📋 模块概述
A2DP(Advanced Audio Distribution Profile)音频传输模块提供高质量音频流传输功能,用于连接蓝牙音频设备(耳机、音箱等)并传输音频数据。
核心类: android.znhaas.bluetooth.BluetoothA2dpManager
连接管理: android.znhaas.bluetooth.BluetoothA2dpConnection
协议处理: android.znhaas.bluetooth.BluetoothA2dpHandler
🎯 主要功能
- ✅ A2DP设备连接/断开
- ✅ 高质量音频流传输
- ✅ 音频播放控制
- ✅ 连接状态监听
- ✅ Handler线程安全处理
- ✅ 支持多设备管理
🏗️ 架构设计
继承统一架构
@RequiresApi(Build.VERSION_CODES.M)
class BluetoothA2dpManager(context: Context) : BaseBluetoothManager<BluetoothStatusListener>(
context, Protocol.A2DP
) {
private val a2dpHandler = BluetoothA2dpHandler()
private val a2dpConnection = BluetoothA2dpConnection(context)
companion object {
// A2DP特定消息类型
private const val MSG_AUDIO_DATA = 10
private const val MSG_START_STREAMING = 11
private const val MSG_STOP_STREAMING = 12
}
}
Handler消息处理
override fun handleProtocolMessage(msg: Message): Boolean {
return when (msg.what) {
MSG_AUDIO_DATA -> {
val audioMsg = msg.obj as AudioDataMessage
handleAudioDataInHandler(audioMsg.deviceAddress, audioMsg.audioData)
true
}
MSG_START_STREAMING -> {
val address = msg.obj as String
handleStartStreamingInHandler(address)
true
}
MSG_STOP_STREAMING -> {
val address = msg.obj as String
handleStopStreamingInHandler(address)
true
}
else -> false
}
}
📚 核心API
1. 初始化
val a2dpManager = BluetoothA2dpManager(context)
a2dpManager.initialize()
2. 连接A2DP设备
connectA2dpDevice(device: BluetoothDeviceInfo): Boolean
val audioDevice = BluetoothDeviceInfo(
address = "AA:BB:CC:DD:EE:FF",
name = "Bluetooth Headset",
deviceType = DeviceType.AUDIO_HEADSET
)
val success = a2dpManager.connectA2dpDevice(audioDevice)
if (success) {
Log.d(TAG, "A2DP设备连接成功")
}
3. 断开连接
disconnectA2dpDevice(address: String): Boolean
a2dpManager.disconnectA2dpDevice("AA:BB:CC:DD:EE:FF")
4. 音频流控制
开始音频流
a2dpManager.startAudioStreaming("AA:BB:CC:DD:EE:FF")
停止音频流
a2dpManager.stopAudioStreaming("AA:BB:CC:DD:EE:FF")
5. 连接状态监听
a2dpManager.setConnectionListener { address, state ->
when (state) {
BluetoothProfile.STATE_CONNECTED -> {
Log.d(TAG, "A2DP已连接: $address")
}
BluetoothProfile.STATE_DISCONNECTED -> {
Log.d(TAG, "A2DP已断开: $address")
}
BluetoothProfile.STATE_CONNECTING -> {
Log.d(TAG, "A2DP连接中: $address")
}
BluetoothProfile.STATE_DISCONNECTING -> {
Log.d(TAG, "A2DP断开中: $address")
}
}
}
🔧 完整使用示例
class BluetoothAudioActivity : AppCompatActivity() {
private lateinit var a2dpManager: BluetoothA2dpManager
private var currentDevice: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_bluetooth_audio)
// 初始化
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
a2dpManager = BluetoothA2dpManager(this)
a2dpManager.initialize()
setupListeners()
}
// 连接按钮
connectButton.setOnClickListener {
connectAudioDevice()
}
// 播放按钮
playButton.setOnClickListener {
currentDevice?.let { addr ->
a2dpManager.startAudioStreaming(addr)
}
}
// 停止按钮
stopButton.setOnClickListener {
currentDevice?.let { addr ->
a2dpManager.stopAudioStreaming(addr)
}
}
}
private fun setupListeners() {
a2dpManager.setConnectionListener { address, state ->
runOnUiThread {
when (state) {
BluetoothProfile.STATE_CONNECTED -> {
currentDevice = address
statusText.text = "已连接音频设备"
playButton.isEnabled = true
stopButton.isEnabled = true
}
BluetoothProfile.STATE_DISCONNECTED -> {
currentDevice = null
statusText.text = "音频设备已断开"
playButton.isEnabled = false
stopButton.isEnabled = false
}
}
}
}
}
private fun connectAudioDevice() {
val device = BluetoothDeviceInfo(
address = "AA:BB:CC:DD:EE:FF",
name = "Bluetooth Headset",
deviceType = DeviceType.AUDIO_HEADSET
)
lifecycleScope.launch(Dispatchers.IO) {
val success = a2dpManager.connectA2dpDevice(device)
withContext(Dispatchers.Main) {
if (success) {
Toast.makeText(this@BluetoothAudioActivity,
"音频设备连接成功", Toast.LENGTH_SHORT).show()
}
}
}
}
override fun onDestroy() {
super.onDestroy()
a2dpManager.cleanup()
}
}
⚠️ 注意事项
1. 系统要求
@RequiresApi(Build.VERSION_CODES.M) // 需要Android 6.0+
2. 权限要求
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
3. Profile连接
A2DP使用Android系统的BluetoothProfile API:
// 自动获取BluetoothA2dp实例
bluetoothAdapter.getProfileProxy(context, serviceListener, BluetoothProfile.A2DP)
4. 音频路由
配合BluetoothAudioRoutingManager实现音频路由切换:
// 切换到蓝牙音频
audioRoutingManager.routeAudioToBluetooth()
// 切换到扬声器
audioRoutingManager.routeAudioToSpeaker()
🔗 相关资源
- 源码:
app/src/main/java/android/znhaas/bluetooth/BluetoothA2dpManager.kt - 音频路由:
android.znhaas.bluetooth.BluetoothAudioRoutingManager - HFP模块: 配合HFP实现完整蓝牙通话功能