android stream audio to server

天涯浪子 提交于 2019-12-18 11:42:18

问题


I would like to understand how socket work, especially I need some code samples for server side to receive the stream sent by mediarecorder from the device.

Thank you very much for any help.

My real final intent is to talk in device and listen it on PC, just one direction.

At moment I am able to send out the stream using the following code:

String hostname = "192.168.1.10";
int port = 8000;
Socket socket = null;
    try {
        socket = new Socket(InetAddress.getByName(hostname), port);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);

recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(pfd.getFileDescriptor());

    try {
        recorder.prepare();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

recorder.start();

回答1:


Seems ok, but I would personally prefer to buffer the audio on the device and send it to the server from another thread instead of tying the recorder to the socket directly like you did. Because buffering locally will allow you to handle connection breaks gracefully.

Imagine you're recording and user goes through a tunnel and loses internet connection -- if you're streaming directly, the socket would close and the user would be annoyed :-) However, if you are buffering the data locally, you can reestablish the connection and continue sending the audio to the server from where you left off, and hopefully the user doesn't even have to know that a break in the connection just happened, because it just magically works.

In order to get that to work, you'd have to write the recording to a local buffer and have a separate thread check for new data on that buffer and send to the server as soon as possible.



来源:https://stackoverflow.com/questions/8576427/android-stream-audio-to-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!