Android使用BluetoothChat通过蓝牙发送音频文件示例
我正在尝试使用蓝牙聊天代码示例通过蓝牙发送音频文件 我创建了一个类,可以将音频转换为字节,反之亦然 下面是我在示例代码中所做的修改Android使用BluetoothChat通过蓝牙发送音频文件示例,android,audio,bluetooth,Android,Audio,Bluetooth,我正在尝试使用蓝牙聊天代码示例通过蓝牙发送音频文件 我创建了一个类,可以将音频转换为字节,反之亦然 下面是我在示例代码中所做的修改 private void sendMessage(String message) { // Check that we're actually connected before trying anything if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(getActivity(), R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
//Convert noti.mp3 into byte array (noti.mp3 is an audio file I am using for testing)
try{send = Converter.convertAudioToBytes(path+"noti.mp3");}
catch(Exception e){Logger.append("Error while converting audio into bytes", e);}
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
我还在音频的末尾添加一些字节,以识别接收端的endofile
在接收端,我已经更新了mHandler
//List to store bytes received from the other device
private List<Byte> list = new ArrayList<Byte>();
case Constants.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
//Status for end of data
boolean endOfData = false;
//Add bytes to the Array list
for(int i=0;i<msg.arg1;i++){list.add(readBuf[i]);}
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName + ": " + readMessage);
//Check if the received message contains this string
//Also check if the length of the data is less than 990
if(readMessage.contains("END OF AUDIO FILE") && msg.arg1<990){
endOfData = true;
}
//Check if all the data has been received
if(endOfData)
{
try{
Converter.convertBytesToAudio(list,path);
mConversationArrayAdapter.add(mConnectedDeviceName + ": Audio saved!");
}
catch(Exception e){
Logger.append("Error while converting bytes to audio", e);
}
finally{
list.clear();
}
}
break;
//存储从其他设备接收的字节的列表
私有列表=新的ArrayList();
case Constants.MESSAGE_读取:
字节[]readBuf=(字节[])msg.obj;
//数据结束状态
布尔值endOfData=false;
//将字节添加到数组列表中
对于(int i=0;i为什么要检查它是否为,因为我接收到的字节数是990,但最后一个字节是音频消息的结尾。
String str = "Message number ";
for(int i=0;i<1000;i++){message += str+i+" ,\n";}
byte[] send = message.getBytes();
mChatService.write(send);