簡體   English   中英

使用Websocket將音頻流從Android(客戶端)發送到C#(服務器)

[英]Send Audio Stream from Android(Client) to C#(Server) using Websocket

我試圖將音頻流/ wav文件作為字節數組從android發送到C#服務器,但無法正確接收,但我能夠收到一個簡單的字符串。

幾秒鍾后C#服務器斷開連接,原因是協議錯誤

協議錯誤:Code = 1002,我認為當文件很大時,幀大小超過並且Web套接字連接丟失。 有出路嗎?

我也嘗試從android發送一個wav文件作為字節數組,如下所示,刪除記錄流:

byte[] buffer = new byte[1024];
                    try {
                        FileInputStream fis = new FileInputStream(file);
                        while(true) {
                            int in = fis.read(buffer, 0, buffer.length);
                                if(in != -1) {
                                    mWebSocket.send(buffer);
                                }else{
                                    break;
                                }
                        }
                    }catch (Exception e) {
                        Log.d("Exception", e.toString());
                    }

Android代碼:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

Button stopPlaying, send, record, stop;
private AudioRecord audiorecord;
private static int SAMPLER = 44100; //Sample Audio Rate
private int channelConfig = AudioFormat.CHANNEL_IN_MONO;
private int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
int minBufSize = AudioRecord.getMinBufferSize(SAMPLER, channelConfig, audioFormat);
private boolean status = true;
URI uri = URI.create("ws://ab1d04d2.ngrok.io");
private String outputFile = null;
private Thread senderThread = null;
private WebSocketClient mWebSocket;
private File file = null;


@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    file = new File(Environment.getExternalStorageDirectory(), "recording.wav");
    setContentView(honeywell.rana.sumit.voicecontrol.R.layout.activity_main);
    audiorecord = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLER, channelConfig, audioFormat, minBufSize);
    send = (Button) findViewById(R.id.send);
    send.setOnClickListener(this);
    stop = (Button) findViewById(R.id.stop);

}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.send:
            AudioTask task = new AudioTask();
            task.execute();
            break;
        case R.id.stop:
            audiorecord.stop();
            mWebSocket.close();
            Log.d("Socket Closed", "");
        default:

            break;
    }
}

public class AudioTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        try {
            mWebSocket = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    Log.d("Connected: ", mWebSocket.getConnection().toString());
                    mWebSocket.send("hello!");                      
                    byte[] buffer = new byte[minBufSize];
                    audiorecord.startRecording();
                    while (true) {
                        int number = audiorecord.read(buffer, 0, minBufSize);
                        for (int i = 0; i < number; i++) {
                            mWebSocket.send(buffer);
                        }
                    }
                }

                @Override
                public void onMessage(String message) {
                        Log.d("Received: ", message);
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    Log.d("Closed", "Code = " + code + ", Reason: " + reason);
                }

                @Override
                public void onError(Exception ex) {
                    Log.d("Error: ", ex.toString());
                }
            };
            mWebSocket.connect();
        } catch (Exception e) {
            Log.d("Exception: ", e.toString());
        }
        return null;
    }
}

}

C#代碼:

namespace ChatServer
{
class Program
{


    static WaveOut waveOut;
    static BufferedWaveProvider bufferedWaveProvider = null;

    private static WebSocketServer appServer = new WebSocketServer();


    static void Main(string[] args)
    {

        Console.WriteLine("Press any key to start the WebSocketServer!");

        Console.ReadKey();
        Console.WriteLine();

        waveOut = new WaveOut();
        bufferedWaveProvider = new BufferedWaveProvider(new WaveFormat(44100, 16, 2));
        waveOut.Init(bufferedWaveProvider);
        waveOut.Play();
        appServer.NewMessageReceived += new SessionHandler<WebSocketSession, string>(appServer_NewMessageReceived);
        appServer.NewDataReceived += new SessionHandler<WebSocketSession, byte[]>(appServer_NewDataReceived);
        appServer.NewSessionConnected += AppServer_NewSessionConnected;           
        appServer.SessionClosed += new SessionHandler<WebSocketSession, CloseReason>(appServer_SessionClosed);    

        //Setup the appServer
        if (!appServer.Setup(80)) //Setup with listening port
        {
            Console.WriteLine("Failed to setup!");
            Console.ReadKey();
            return;
        }

        //Try to start the appServer
        if (!appServer.Start())
        {
            Console.WriteLine("Failed to start!");
            Console.ReadKey();
            return;
        }

        Console.WriteLine("The server started successfully, press key 'q' to stop it!");

        while (Console.ReadKey().KeyChar != 'q')
        {
            Console.WriteLine();
            continue;
        }

        //Stop the appServer
        appServer.Stop();
        Console.WriteLine();
        Console.WriteLine("The server was stopped!");
        Console.ReadKey();
    }

    private static void AppServer_NewSessionConnected(WebSocketSession session)
    {
        Console.WriteLine("New Client connected: " + session.SessionID);
    }

    static void appServer_SessionClosed(WebSocketSession session, CloseReason reason)
    {
        Console.WriteLine(reason);
    }

    static void appServer_NewDataReceived(WebSocketSession session, byte[] value)
    {

        bufferedWaveProvider.AddSamples(value, 0, value.Length);

    }

    static void appServer_NewMessageReceived(WebSocketSession session, string message)
    {
        //Send the received message back

        session.Send("Server: " + message);
        Console.WriteLine(message);
    }

我終於完成了它,這只是一個小問題。 我只是將android中的緩沖區大小減少到了64/128/512,現在它的工作正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM