|
|
|
@ -132,6 +132,23 @@ object BleService { |
|
|
|
// 初始化状态 |
|
|
|
private var isInitialized = false |
|
|
|
|
|
|
|
// 音频数据统计相关变量 |
|
|
|
private var bytesReceivedInCurrentSecond = 0 |
|
|
|
private var lastStatisticsTime = System.currentTimeMillis() |
|
|
|
private val statisticsHandler = Handler(Looper.getMainLooper()) |
|
|
|
private val statisticsRunnable = object : Runnable { |
|
|
|
override fun run() { |
|
|
|
val currentTime = System.currentTimeMillis() |
|
|
|
val timeDiff = currentTime - lastStatisticsTime |
|
|
|
if (timeDiff >= 1000) { // 每秒统计一次 |
|
|
|
Log.i(TAG, "每秒接收音频数据: $bytesReceivedInCurrentSecond 字节") |
|
|
|
bytesReceivedInCurrentSecond = 0 |
|
|
|
lastStatisticsTime = currentTime |
|
|
|
} |
|
|
|
statisticsHandler.postDelayed(this, 1000) // 每秒执行一次 |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
private val replyTimeoutHandler = Handler(Looper.getMainLooper()) |
|
|
|
private val replyTimeoutRunnable = Runnable { |
|
|
|
if (!isReply) { |
|
|
|
@ -567,6 +584,20 @@ object BleService { |
|
|
|
notifyConnectionStateChanged(state) |
|
|
|
} |
|
|
|
|
|
|
|
// 在连接成功时启动统计(可以在onConnectionStateChange的连接成功分支中添加) |
|
|
|
private fun startBytesStatistics() { |
|
|
|
bytesReceivedInCurrentSecond = 0 |
|
|
|
lastStatisticsTime = System.currentTimeMillis() |
|
|
|
statisticsHandler.post(statisticsRunnable) |
|
|
|
Log.i(TAG, "开始统计每秒接收字节数") |
|
|
|
} |
|
|
|
|
|
|
|
// 在断开连接时停止统计 |
|
|
|
private fun stopBytesStatistics() { |
|
|
|
statisticsHandler.removeCallbacks(statisticsRunnable) |
|
|
|
Log.i(TAG, "停止统计每秒接收字节数") |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
|
* GATT回调 |
|
|
|
*/ |
|
|
|
@ -618,7 +649,7 @@ object BleService { |
|
|
|
return |
|
|
|
} |
|
|
|
Log.d(TAG, "找到通话音频服务所需特征") |
|
|
|
|
|
|
|
startBytesStatistics() |
|
|
|
writeChar?.writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE |
|
|
|
callWriteChar?.writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE |
|
|
|
//要先设置音频服务的通知,否则接收不到 |
|
|
|
@ -643,7 +674,9 @@ object BleService { |
|
|
|
when (c.uuid) { |
|
|
|
// 音频特征数据 |
|
|
|
BleConst.RECEIVE_AUDIO_CHAR_UUID -> { |
|
|
|
|
|
|
|
|
|
|
|
// 统计接收到的字节数 |
|
|
|
bytesReceivedInCurrentSecond += data.size |
|
|
|
processAudioData(data) |
|
|
|
} |
|
|
|
// 通知特征数据(命令和控制) |
|
|
|
@ -720,10 +753,12 @@ object BleService { |
|
|
|
*/ |
|
|
|
private fun processAudioData(data: ByteArray) { |
|
|
|
try { |
|
|
|
|
|
|
|
|
|
|
|
if (opusManager?.isDecodeStream == true) { |
|
|
|
recordfile?.saveAudioDataToWav(data) |
|
|
|
// 将完整的帧加入队列,由专门的线程处理 |
|
|
|
audioDataQueue.offer(data) |
|
|
|
// 将完整的帧加入队列,由专门的线程处理 |
|
|
|
audioDataQueue.offer(data) |
|
|
|
// // 将接收到的数据添加到缓存中 |
|
|
|
// synchronized(audioDataBuffer) { |
|
|
|
// audioDataBuffer.addAll(data.toList()) |
|
|
|
@ -741,7 +776,7 @@ object BleService { |
|
|
|
// } |
|
|
|
// } |
|
|
|
} else { |
|
|
|
Log.d(TAG, "Opus解码流未启动,忽略音频数据") |
|
|
|
// Log.d(TAG, "Opus解码流未启动,忽略音频数据") |
|
|
|
} |
|
|
|
} catch (e: Exception) { |
|
|
|
Log.e(TAG, "处理音频数据异常: ${e.message}", e) |
|
|
|
|