如何将通过蓝牙接收的数据传输到Android设备之间的mp3文件中?

时间:2012-09-11 03:21:17

标签: android bluetooth mp3 send file-transfer

问题:如何将收到的数据(通过蓝牙聊天示例代码发送)传输到mp3文件中?

目的:使用简单的蓝牙文件传输方法将mp3文件从一部Android手机传输到另一部手机。

方法:使用Android SDK提供的蓝牙聊天示例,我将MP3文件传输到一个字节数组,然后将数据传输到第二个设备。

当前状态:数据由第二个设备接收(我通过将流输出到屏幕来检查)但是我无法打开文件并将数据传输到其中,给它一个“.mp3”扩展名和然后播放它。

BluetoothChat.java

public byte[] lilfilebuffer = null;


private void sendMessage(String message) {


    lilfilebuffer = read(new File("/sdcard/media/07_The-organ.mp3"));
    mChatService.write(lilfilebuffer);


}


private byte[] read(final File file) {
    Throwable pending = null;
    FileInputStream in = null;
    final byte buffer[] = new byte[(int) file.length()];
    try {
        in = new FileInputStream(file);
        in.read(buffer);
    } catch (Exception e) {
        pending = new RuntimeException("Exception occured on reading file "
                        + file.getAbsolutePath(), e);
    } finally {
        if (in != null) {
                try {
                        in.close();
                } catch (Exception e) {
                        if (pending == null) {
                                pending = new RuntimeException(
                                        "Exception occured on closing file" 
                             + file.getAbsolutePath(), e);
                        }
                }
        }
        if (pending != null) {
                throw new RuntimeException(pending);
        }
    }
    return buffer;
}




// The Handler that gets information back from the BluetoothChatService
private final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case MESSAGE_STATE_CHANGE:
            if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
            switch (msg.arg1) {
            case BluetoothChatService.STATE_CONNECTED:
                setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
                mConversationArrayAdapter.clear();
                break;
            case BluetoothChatService.STATE_CONNECTING:
                setStatus(R.string.title_connecting);
                break;
            case BluetoothChatService.STATE_LISTEN:
            case BluetoothChatService.STATE_NONE:
                setStatus(R.string.title_not_connected);
                break;
            }
            break;
        case MESSAGE_WRITE:
            byte[] writeBuf = (byte[]) msg.obj;

            try {
                FileOutputStream out = new FileOutputStream("/sdcard/media/testsong.mp3");
                out.write(writeBuf);
                out.close();

                } 
                catch (IOException e) 
                { 
                //System.out.println("Exception ");

                }
            break;
        case MESSAGE_READ:
            byte[] readBuf = (byte[]) msg.obj;

            try {
                FileOutputStream out = new FileOutputStream("/sdcard/media/testsong.mp3");

                out.write(readBuf);
                out.close();



                } 
                catch (IOException e) 
                { 
                //System.out.println("Exception ");

                }



            break;
        case MESSAGE_DEVICE_NAME:
            // save the connected device's name
            mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
            Toast.makeText(getApplicationContext(), "Connected to "
                           + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
            break;
        case MESSAGE_TOAST:
            Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                           Toast.LENGTH_SHORT).show();
            break;
        }
    }
};

BluetoothChatService.java

public void write(byte[] out) {

    ConnectedThread r;

    synchronized (this) {
        if (mState != STATE_CONNECTED) return;
        r = mConnectedThread;
    }

    r.write(out);
}

private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket, String socketType) {
        Log.d(TAG, "create ConnectedThread: " + socketType);
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;


        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "temp sockets not created", e);
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        Log.i(TAG, "BEGIN mConnectedThread");
        byte[] buffer = new byte[1024];
        int bytes;


        while (true) {
            try {

                bytes = mmInStream.read(buffer);


                mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                // Start the service over to restart listening mode
                BluetoothChatService.this.start();
                break;
            }
        }
    }

    public void write(byte[] buffer) {
        try {
            mmOutStream.write(buffer);


            mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer)
                    .sendToTarget();
        } catch (IOException e) {
            Log.e(TAG, "Exception during write", e);
        }
    }


}}

1 个答案:

答案 0 :(得分:0)

数据或MP3文件没有什么特别之处。你只需要在播放之前把它写到磁盘上。

我有一个应用程序(BlueMuze)完全执行此操作,我发现更难的部分是建立和维护蓝牙连接以及使配对时间正确。

然而,您的代码存在的问题是您似乎每1024字节创建并写入一个新文件。

每次“聊天”处理程序读取服务发送的消息时,您都会创建一个新的FileOutputStream。相反,您只需要创建FileOutputStream一次并将缓冲区写入它,直到到达文件末尾,然后关闭FileOutputStream

希望有所帮助。