如何在servlet(webservice)中将byte []转换为.mp4音频文件

时间:2011-12-22 06:04:22

标签: android servlets

我在android中录制了语音并格式化为.mp3音频文件,并通过使用base 64编码将其作为名称值对发送。现在在我的服务器端,即在我的servlet中,我获取值并将其解码为byte [ ]使用base 64

我的客户端代码(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;
        }
    }
}

我的服务器端代码(在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");
        }

                }   



}

}

在我的servlet中做什么火腿只是获取byte []并直接将其保存在一个带有位置的文件中但我想要的是在获取byte []后我想将其转换为.mp3音频文件并将其保存在某些文件中路径..我不知道如何在获取byte []到.mp3音频文件之后继续这个...可以任何一个PLZ帮助我..

2 个答案:

答案 0 :(得分:0)

如果要将MP4数据记录到文件,读取它,base64编码,传输,base64解码,将字节写入文件,那么它已经是目的地的MP4。你收到错误吗?

答案 1 :(得分:0)

  

InputStream is = Context.openFileInput(someFileName); //无论你有什么形式

     

ByteArrayOutputStream bos = new ByteArrayOutputStream();

     

byte [] b =新字节[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();

使用 audioDataString 并将此audioDataString发送到namevaluepair对象