I am trying to send an audio file via Bluetooth using a sample bluetooth code.
I created a class that converts audio to bytes and vice versa.
Here are the modifications I made in the sample code
private void sendMessage(String message) {
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(getActivity(), R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
byte[] send = message.getBytes();
try{send = Converter.convertAudioToBytes(path+"noti.mp3");}
catch(Exception e){Logger.append("Error while converting audio into bytes", e);}
mChatService.write(send);
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
I also add a few bytes at the end of the audio to identify the endOfFile on the receiving side.
In the front end, I updated mHandler
private List<Byte> list = new ArrayList<Byte>();
case Constants.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
boolean endOfData = false;
for(int i=0;i<msg.arg1;i++){list.add(readBuf[i]);}
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName + ": " + readMessage);
if(readMessage.contains("END OF AUDIO FILE") && msg.arg1<990){
endOfData = true;
}
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;
This code works great for small audio files, but when I send a file larger than 3 KB, it receives data incorrectly and does not transmit it to audio.
I tried to send a long text like this
String str = "Message number ";
for(int i=0;i<1000;i++){message += str+i+" ,\n";}
byte[] send = message.getBytes();
mChatService.write(send);
on the receiving side, which I noticed, the received messages are not synchronized.
- Bluetooth. - WhatsApp, Bluetooth.
.
:( ,