0

Estou criando um Mural em que as pessoas poderão enviar mensagem de texto e áudio para um servidor php, as mensagens de texto e o mural funcionam perfeitamente, mas não tenho ideia de como armazenar um áudio gravado e envia-lo logo em seguida.

Vi alguns exemplos na internet e estou utilizando este código abaixo:

Para realizar a gravação de audio:

private void stopRecording(){
    if(recorder != null) recorder.stop();
}

private void beginRecording() throws IOException, InterruptedException {
    ditchMediaRecorder();
    File outFile = new File(OUTPUT_FILE);

    if(outFile.exists()) outFile.delete();

    recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    recorder.setOutputFile(OUTPUT_FILE);
    recorder.prepare();
    recorder.start();
}

private void ditchMediaRecorder(){
    if(recorder != null) recorder.release();
}

Para realizar o Envio: (Não sei se esta correto este envio porque não estou conseguindo receber nada no servidor php)...

public void enviaAudioServer(View v) {
    new LongOperationAudio().execute("");
}

private class LongOperationAudio extends AsyncTask<String, Void, String> {
    String name = nome.toString();
    String mail = email.toString();

    ProgressBar carrega = (ProgressBar) findViewById(R.id.carregaMsg);

    @Override
    protected String doInBackground(String... params) {
        try {
            final ByteArrayOutputStream out = new ByteArrayOutputStream();
            final InputStream in = new FileInputStream(outFile); //Outfile usei pra fazer a gravação . . .
            final byte[] buf = new byte[2048];
            int n;
            while ((n = in.read(buf)) >= 0) {
                out.write(buf, 0, n);
            }

            final byte[] data = out.toByteArray();
            String urlString = "http://www.siteServidorPHP.com.br/mural/listener.php?a=13";
            HttpPost postRequest = new HttpPost(urlString);

            postRequest.setEntity(new ByteArrayEntity(data));
            HttpClient client = new DefaultHttpClient();
            HttpResponse response = client.execute(postRequest);
            HttpEntity entity = response.getEntity();
            InputStream ins = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(ins));
            String temp_str;
            StringBuilder sb = new StringBuilder();
            while((temp_str = br.readLine()) != null) {
                sb.append(temp_str);
            }
            Log.e("response", sb.toString());


        } catch (Exception e) {
            // handle exception here
            Log.e(e.getClass().getName(), e.getMessage());
            return "exception";
        }
          return null;
    }

    @Override
    protected void onPostExecute(String result) {
        carrega.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void onPreExecute() {
        carrega.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}

Quando executo aparece o seguinte erro no logcat:

E/response: 403 Forbidden

Forbidden

You don't have permission to access /mural/listener.phpon this server.

Additionally, a 404 Not Founderror was encountered while trying to use an ErrorDocument to handle the request.

Caso alguém saiba alguma forma de enviar o áudio e receber áudios também, toda dica ou sugestão é bem vinda.

Obrigado!

5
  • 1
    Então você pode transformar em um array de bytes [] esse seu file(audio) então assim enviar para o seu servidor! Pesquise como converter um file para bytes e você vai conseguir tranquilo 18/12/2015 às 18:08
  • Vou tentar aqui, caso consiga ou não, aviso. Obrigado! 18/12/2015 às 18:28
  • Olá Alessandro, tentei fazer da forma que me sugeriu, porem, infelizmente ainda não consegui. Postei a última versão do código na pergunta para que você possa ver, caso identifique o problema, por favor informe. Obrigado pela atenção. 21/12/2015 às 17:02
  • 1
    Porque não usa lib Retrofit2.0? Ela é bastante simples de utilizar. 21/12/2015 às 23:25
  • Blz, vou dar uma lida sobre ela e tentar aqui, caso consiga ou não, aviso. Obrigado pela dica! 22/12/2015 às 11:31

0

Você deve fazer log-in para responder a esta pergunta.

Pesquise outras perguntas com a tag .