Android使用蓝牙通过蓝牙发送音频文件

时间:2017-09-26 10:26:35

标签: android audio bluetooth

我正在尝试使用示例BluetoothChat代码通过蓝牙发送音频文件。

我创建了一个将音频转换为字节的类,反之亦然。

以下是我在示例代码

中所做的修改
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);
    }
}

我还在音频末尾添加了一些字节,以识别接收端的endOfFile。

在接收端,我更新了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;

该代码适用于小型音频文件,但是当我发送大于3KB的文件时,它无法正确接收数据并且无法正确传输到音频。

我尝试发送一些像这样的长文本

String str = "Message number ";
for(int i=0;i<1000;i++){message += str+i+" ,\n";}
byte[] send = message.getBytes();
mChatService.write(send);

在接收端我注意到,收到的消息不同步。

有人可以帮我解决这个问题,或通过蓝牙传输音频信息的任何其他方式。我正在尝试做类似WhatsApp音频消息但通过蓝牙。

感谢任何帮助。谢谢

仍在等待答案:(请帮忙

0 个答案:

没有答案
相关问题