🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

How to connect and stream to a server using MediaRecorder, Socket and ParcelFileDescriptor. Android Studio

Started by
3 comments, last by hplus0603 4 years, 3 months ago

on the client side I have this code

Socket socket = new Socket("10.0.0.10", 7800);
                            ParcelFileDescriptor socketWrapper = ParcelFileDescriptor.fromSocket(socket);
                            mediaRecorder = new MediaRecorder();
                            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                            mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
                            mediaRecorder.setOutputFile(socketWrapper.getFileDescriptor());
                            mediaRecorder.prepare();
                            mediaRecorder.start();

How do I send this audio to a C ++ server and re-stream it to others using the app?

Server code

// Iniciarlizar winsock
WSADATA wsData;
WORD ver = MAKEWORD(2, 2);

int wsOk = WSAStartup(ver, &wsData);
if (wsOk != 0)
{
    sampgdk::logprintf("Não foi possivel inicializar o winsock! Fechando...!");
    return;
}

// Criar o soquete
SOCKET escutando = socket(AF_INET, SOCK_STREAM, 0);
if (escutando == INVALID_SOCKET)
{
    sampgdk::logprintf("Não foi possível criar um socket! Fechando...");
    return;
}
// Ligue a um endereço IP e a porta a um soquete
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(54000);
hint.sin_addr.S_un.S_addr = INADDR_ANY;

bind(escutando, (sockaddr*)&hint, sizeof(hint));

// Diga ao winsock que o soquete é para ouvir
listen(escutando, SOMAXCONN);

// aguarde uma conexão

sockaddr_in client;
int clientSize = sizeof(client);

SOCKET clientSocket = accept(escutando, (sockaddr*)&client, &clientSize);

char host[NI_MAXHOST];  // Client's remote name
char service[NI_MAXHOST]; // Service (i.e port) the client is connect on

ZeroMemory(host, NI_MAXHOST);
ZeroMemory(service, NI_MAXHOST);

if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0)
{
    cout << host << " Conectado na porta " << service << endl;
}
else
{
    inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
    cout << host << " Conexão na porta " <<
        ntohs(client.sin_port) << endl;
}

// tomada de escuta próxima
closesocket(escutando);

// while loop: aceita e faz eco da mensagem de volta ao cliente
char buf[4096];
while (true) 
{
    ZeroMemory(buf, 4096);

    // Wait for client to send data
    int bytesReceived = recv(clientSocket, buf, 4096, 0);
    if (bytesReceived == SOCKET_ERROR)
    {
        cerr << "Error in recv(). Fechando" << endl;
        break;
    }

    if (bytesReceived == 0)
    {
        cout << "Client disconnected" << endl;
        break;
    }

    send(clientSocket, buf, bytesReceived + 1, 0);
    // Echo message back to client
}

// Feche o soquete
closesocket(clientSocket);

// Desligar winsock
WSACleanup();
Advertisement

That server just accepts the first connection, and then doesn't accept anymore. Is that what you want?

Streaming audio is pretty advanced – generally, TCP is the wrong choice for that; you'll want to use UDP packets.

You'll also want to use a codec that's intended for online streaming and has some mitigation of packet loss, such as OPUS. (If you use something not-C on the client side, you'd have to link to the OPUS C library, or find some package that already does that.)

enum Bool { True, False, FileNotFound };

@undefined i have this error using opus

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.playvicio.voippv-wBH657StDF-Wh1S2Rmebhw==/base.apk"],nativeLibraryDirectories=[/data/app/com.playvicio.voippv-wBH657StDF-Wh1S2Rmebhw==/lib/arm64, /system/lib64]]] couldn't find "libsenz.so"

That's a linker error. If you're not comfortable with your development tools, you should probably not be trying to build internet real-time audio chat applications yet. I've seen people try it before before they were ready, and it never ends well.

enum Bool { True, False, FileNotFound };

This topic is closed to new replies.

Advertisement