-3

I have recorded voice and formatted as .mp3 audio file in android and sending it as name value pair by encoding using base 64.. Now In my server side i.e. in my servlet i am getting the value and decoding it into byte[] using base 64

my client side code(android):

package com.android.audio;

import android.app.Activity;
import android.widget.LinearLayout;
import android.os.Bundle;
import android.os.Environment;
import android.view.ViewGroup;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.content.Context;
import android.util.Base64;
import android.util.Log;
import android.media.MediaRecorder;
import android.media.MediaPlayer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.commons.io.FileUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;



public class AudioRecordActivity extends Activity
{
    private static final String LOG_TAG = "AudioRecordTest";
    private static String mFileName = null;
    private String url = "QRFileSaveServlet";
    String result;
    byte[] value;
    String s;
    byte[] filebyte;;
     String readString;
    private RecordButton mRecordButton = null;
    private MediaRecorder mRecorder = null;
   private SubmitButton mSubmitButton = null;
    private PlayButton   mPlayButton = null;
    private MediaPlayer   mPlayer = null;
    String fileresult = "";;
    private void onRecord(boolean start) {
        if (start) {
            startRecording();
        } else {
            stopRecording();
        }
    }

    private void onPlay(boolean start) {
        if (start) {
            startPlaying();
        } else {
            stopPlaying();
        }
    }

    private void startPlaying() {
        mPlayer = new MediaPlayer();
        try {
            mPlayer.setDataSource(mFileName);
            mPlayer.prepare();
            mPlayer.start();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }
    }

    private void stopPlaying() {
        mPlayer.release();
        mPlayer = null;
    }

    private void startRecording() {
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
        mRecorder.setOutputFile(mFileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            mRecorder.prepare();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }

        mRecorder.start();
    }
    /* public boolean saveas(int ressound){  
             byte[] buffer=null;  
             InputStream fIn = getBaseContext().getResources().openRawResource(ressound);  
             int size=0;  

             try {  
              size = fIn.available();  
              buffer = new byte[size];  
              fIn.read(buffer);  
             fIn.close();  
            } catch (IOException e) {  
             // TODO Auto-generated catch block  
            return false;  
            }  

            String path="/sdcard/media/audio/ringtones/";  
            String filename="examplefile"+".ogg";  

            boolean exists = (new File(path)).exists();  
            if (!exists){new File(path).mkdirs();}  

            FileOutputStream save;  
            try {  
             save = new FileOutputStream(path+filename);  
             save.write(buffer);  
             save.flush();  
             save.close();  
            } catch (FileNotFoundException e) {  
             // TODO Auto-generated catch block  
             return false;  
            } catch (IOException e) {  
             // TODO Auto-generated catch block  
             return false;  
            }      

            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));  

            File k = new File(path, filename);  

            ContentValues values = new ContentValues();  
            values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());  
            values.put(MediaStore.MediaColumns.TITLE, "exampletitle");  
            values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");  
            values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");  
            values.put(MediaStore.Audio.Media.IS_RINGTONE, true);  
            values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);  
            values.put(MediaStore.Audio.Media.IS_ALARM, true);  
            values.put(MediaStore.Audio.Media.IS_MUSIC, false);  

            //Insert it into the database  
            this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);  


            return true;  
           }  */
    private void stopRecording() {
        mRecorder.stop();
        mRecorder.release();
      //  mRecorder.reset();
        mRecorder = null;
    }

    class RecordButton extends Button {
        boolean mStartRecording = true;

        OnClickListener clicker = new OnClickListener() {
            public void onClick(View v) {
                onRecord(mStartRecording);
                if (mStartRecording) {
                    setText("Stop recording");
                } else {
                    setText("Start recording");
                }
                mStartRecording = !mStartRecording;
            }
        };

        public RecordButton(Context ctx) {
            super(ctx);
            setText("Start recording");
            setOnClickListener(clicker);
        }
    }

    class PlayButton extends Button {
        boolean mStartPlaying = true;

        OnClickListener clicker = new OnClickListener() {
            public void onClick(View v) {
                onPlay(mStartPlaying);
                if (mStartPlaying) {
                    setText("Stop playing");
                } else {
                    setText("Start playing");
                }
                mStartPlaying = !mStartPlaying;
            }
        };

        public PlayButton(Context ctx) {
            super(ctx);
            setText("Start playing");
            setOnClickListener(clicker);
        }

    }
   class SubmitButton extends Button {

        OnClickListener clicker = new OnClickListener() {

            public void onClick(View v) {



                       File f = new File(Environment.getExternalStorageDirectory()+"/audiorecordtest.mp3");
//                     
                //byte[] file = fileresult.getBytes();

                try {
                    filebyte = FileUtils.readFileToByteArray(f);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                System.out.println("$$$$$$$$$$$" + filebyte);
                s = Base64.encodeToString(filebyte, MODE_APPEND);
                System.out.println("**************" + s);

                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("Audiofile", s));
                result = AudioServer.executePost(url, nameValuePairs);

            }

        };
        public SubmitButton(Context ctx) {
            super(ctx);
            setText("Save");
            setOnClickListener(clicker);
        }
            }

    public AudioRecordActivity() {
        mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
        mFileName += "/audiorecordtest.mp3";
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        LinearLayout ll = new LinearLayout(this);
        mRecordButton = new RecordButton(this);
        ll.addView(mRecordButton,
            new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                0));
        mPlayButton = new PlayButton(this);
        ll.addView(mPlayButton,
            new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                0));
    mSubmitButton = new SubmitButton(this);
        ll.addView(mSubmitButton, new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, 0));

        setContentView(ll);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }

        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }
}

my server side code(in servlet):

package com.gsr.qrbarcode;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import com.android.gsr.utils.AudioSampleReader;
import com.android.gsr.utils.AudioSampleWriter;
import com.android.gsr.utils.Base64;

import javax.servlet.ServletException;
//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFileFormat.Type;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

import org.apache.commons.io.FileUtils;


/**
 * Servlet implementation class QRFileSaveServlet
 */
//@WebServlet("/QRFileSaveServlet")
public class QRFileSaveServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public QRFileSaveServlet() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub


        String qrfile= request.getParameter("Audiofile");

        byte[] audiofile=Base64.decode(qrfile);
         String newStr = new String(audiofile);


            // Display the contents of the byte array.
           System.out.println("The new String equals \"" +newStr + "\"");
            String filePath = this.getServletContext().getRealPath("/")+"";
            System.out.println("Path of the file " + filePath);
            String fileupload="AudioFileStorage";
            PrintWriter out = response.getWriter();


            File f;

                f= new File(filePath);

                //int status = 0;
                if(f.exists()) {
                    filePath += fileupload;

                    f = new File(filePath);
                    if(!f.exists()){
                        f.mkdir();
                    }



                    f = new File(filePath,"test");
                    if(!f.exists()) {
                        FileOutputStream fos = new FileOutputStream(f);

                        fos.write(audiofile);
                        fos.flush();
                        fos.close();
                    } else {
                        out.println("failure");
        }

                }   



}

}

what ham doing in my servlet is just getting byte[] and directly saving it in a file with location but what i want is after getting the byte[] i want to convert it into .mp3 audio file and save it in some path.. i dont know how to continue this after getting byte[] to .mp3 audio file... can any one plz help me..

4
  • no not necessary to convert byte[] i just want to get through request.getparameter and save it as .mp3 audio file in my server side and save it in some path location
    – pratibha
    Dec 22, 2011 at 6:19
  • My understanding is that your android client does send and MP3 file. So there is no need to convert MP3 to MP3 on your server! Or do I miss anything?
    – home
    Dec 22, 2011 at 6:19
  • then i have a doubt, when i get an mp3 file as byte[] from my android client ,how should i save it in my server side as a .mp3 file. i.e. i should have for example "audiorecord.mp3" file being created in my server side destination. when i click that .mp3 file that should be played in my server side also.
    – pratibha
    Dec 22, 2011 at 9:25
  • sorry there is mistake in my question ham already getting as mp3 file from android so no need to convert it to mp3 i just want to play that mp3 in server side. i.e. i should have for example "audiorecord.mp3" file being created in my server side destination.
    – pratibha
    Dec 22, 2011 at 9:39

2 Answers 2

0

If you are recording MP4 data to a file, reading it, base64 encoding, transmitting, base64 decoding, writing bytes to a file then it is MP4 at the destination already. Are you getting an error?

3
  • no ham not getting any error...a text fileis being created in my destination with named as " test" in which ham having binary values being saved
    – pratibha
    Dec 22, 2011 at 9:14
  • ya ur exactly correct im getting mp4 bytes in my destination as text file but what i want to achieve is i want to play that audio and c for that i should have a .mp4 file created instead of text file so that i can play that file. for example in my client side an audio file with .mp4 is being created in sdcard like that it should be created in my server side destination also
    – pratibha
    Dec 22, 2011 at 9:34
  • sorry pratibha, I don't know what you mean Dec 23, 2011 at 1:46
0

InputStream is = Context.openFileInput(someFileName); // whatever formate you have

ByteArrayOutputStream bos = new ByteArrayOutputStream();

byte[] b = new byte[1024]; while ((int bytesRead = is.read(b)) != -1) {

        bos.write(b, 0, bytesRead);

}

byte[] bytes = bos.toByteArray(); String audioDataString=Base64.encodeToString(bytes,Base64.NO_WRAP).toString();

Use audioDataString and send this audioDataString in to namevaluepair Object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.