如何将音频文件从android客户端发送到servlet服务器

时间:2011-12-26 05:10:41

标签: android servlets

我想将一个音频文件.mp3文件从android客户端发送到servlet服务器并将其保存在一个位置。如果我在该位置播放保存的.mp3文件,它应该播放。 我的问题是有一种方法可以直接从客户端向服务器发送.mp3文件,并在servlet中检索该mp3文件。

我的客户端代码如下:

package com.android.audiorecord;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.android.audiofileplayer.StreamingMp3Player;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

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,clientbyte;
     String readString;
    private RecordButton mRecordButton = null;
    private MediaRecorder mRecorder = null;
   private SubmitButton mSubmitButton = null;
    private PlayButton   mPlayButton = null;
    private MediaPlayer   mPlayer = null;
    String fileresult = "";
    HttpResponse response;
    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);
                clientbyte = Base64.encode(filebyte, MODE_APPEND);//(filebyte, MODE_APPEND);
                s= new String(clientbyte);
                System.out.println("**************" + s);

                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("Audiofile", s));
                result = AudioServer.executePost(url, nameValuePairs);
                result = result.trim();
                System.out.println("response recieved " + result);
                if(result!=null){
                    Bundle bundle = new Bundle();
                    Intent explicitIntent = new Intent(AudioRecordActivity.this,
                            StreamingMp3Player.class);
                    bundle.putString("result", result);
                    explicitIntent.putExtras(bundle);
                    startActivity(explicitIntent);
                }

            }

        };
        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;
        }
    }
}

在此我可以将audiorecordtest.mp3文件直接发送到服务器而无需编码为byte []并以namevalue对的形式发送。

我的服务器端代码如下:

package com.gsr.qrbarcode;
import java.io.BufferedInputStream;
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 java.net.MalformedURLException;
import java.net.URL;
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.ServletOutputStream;
//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;
    AudioInputStream ais;
    /**
     * 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");
        System.out.println("String Parameter \"" +qrfile );
        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.mp3");
                    if(!f.exists()) {
                        FileOutputStream fos = new FileOutputStream(f);

                        fos.write(audiofile);
                        fos.flush();
                        fos.close();
                    } else {
                        //out.println("failure");
                        ServletOutputStream stream = null;
                          BufferedInputStream buf = null;
                          try{

                          stream = response.getOutputStream();
                         // File mp3 = new File(mp3Dir + "/" + fileName);

                          response.setContentType("audio/mpeg");

                          response.addHeader("Content-Disposition","attachment; filename="+f );

                          response.setContentLength( (int) f.length() );

                          FileInputStream input = new FileInputStream(f);
                          buf = new BufferedInputStream(input);
                          int readBytes = 0;

                          while((readBytes = buf.read()) != -1)
                             stream.write(readBytes);
                          System.out.println("Response Stream"+stream);

                         } catch (IOException ioe){

                            throw new ServletException(ioe.getMessage());

                         } finally {
                         if(stream != null)
                             stream.close();
                          if(buf != null)
                              buf.close();
                              }
        }

                }   
                 if (filePath == null || filePath.equals(""))
                       throw new ServletException(
                         "Invalid or non-existent mp3Dir context-param.");
                 URL url = null;

                 try{

                 url = f.toURL();

                  System.out.println("URL : "+ url);

                  System.out.println("Converting process Successfully");

                 }

                  catch (MalformedURLException me){

                  System.out.println("Converting process error");

                  }
                //String rfilepath=this.getServletContext().getRealPath("/")+" AudioFileStorage/test.mp3";
                //System.out.println("Path of the rfilepath " + rfilepath);



}


}

这里可以直接从客户端获取audiorecordtest.mp3文件而无需在服务器端解码并在此servlet中播放

我在本地的客户端服务器连接 executepost()如下:

package com.android.audio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

public class AudioServer {

    static InputStream is;
    private static String API_URL = "http://192.168.15.71:8088/QRBarCodeServer/";

    public static String executePost(String apiurl,
            ArrayList<NameValuePair> urlParameters) {

        try {
            // Create connection

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(API_URL + apiurl);

            httppost.setEntity(new UrlEncodedFormEntity(urlParameters));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

            // Get Response
            // InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response1 = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response1.append(line);
                response1.append('\r');
            }
            rd.close();

            return response1.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String executeHttpGet(String apiurl) throws Exception {

        BufferedReader in = null;

        try {

            HttpClient client = new DefaultHttpClient();

            HttpGet request = new HttpGet(API_URL + apiurl);

            request.setURI(new URI(apiurl));

            HttpResponse response = client.execute(request);

            in = new BufferedReader(new InputStreamReader(response.getEntity()
                    .getContent()));

            StringBuffer sb = new StringBuffer("");

            String line = "";

            String NL = System.getProperty("line.separator");

            while ((line = in.readLine()) != null) {

                sb.append(line + NL);

            }

            in.close();

            String result = sb.toString();

            return result;

        } finally {

            if (in != null) {

                try {

                    in.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }

}

3 个答案:

答案 0 :(得分:2)

这是一种简单的方法

1:从android端读取.mp3文件并从中创建base64String。 2:在servier端读取这个base64String并将其转换回.mp3文件。

将任何文件转换为base64String以下是进程

File file = new File(Environment.getExternalStorageDirectory() + "/hello-4.wav");
byte[] bytes = FileUtils.readFileToByteArray(file);

String encoded = Base64.encodeToString(bytes, 0); 

答案 1 :(得分:1)

您可以使用apache MultipartEntity:

来访问它
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(BASE_URL);
MultipartEntity mpEntity  = new MultipartEntity();
mpEntity.addPart("Audiofile", new FileBody(file, "audio/mpeg")); 
post.setEntity(mpEntity);
HttpResponse res = client.execute(post);    

答案 2 :(得分:0)

是的,你可以在Servlet中发送这个Mime类型的mime意味着多媒体扩展 我发送代码我可以保证它将在Java中的Servlet中工作,你应该采取 自己照顾安卓

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SendMp3Envious extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
String fileName = (String) request.getParameter("file");
if (fileName == null || fileName.equals(""))
  throw new ServletException(
      "Invalid or non-existent file parameter in SendMp3 servlet.");

  if (fileName.indexOf(".mp3") == -1)
  fileName = fileName + ".mp3";

String mp3Dir = getServletContext().getInitParameter("mp3-dir");
if (mp3Dir == null || mp3Dir.equals(""))
  throw new ServletException(
      "Invalid or non-existent mp3Dir context-param.");

ServletOutputStream stream = null;
BufferedInputStream buf = null;
try {

  stream = response.getOutputStream();
  File mp3 = new File(mp3Dir + "/" + fileName);

  //set response headers
  response.setContentType("audio/mpeg");

  response.addHeader("Content-Disposition", "attachment; filename="
      + fileName);

  response.setContentLength((int) mp3.length());

  FileInputStream input = new FileInputStream(mp3);
  buf = new BufferedInputStream(input);
  int readBytes = 0;
  //read from the file; write to the ServletOutputStream
  while ((readBytes = buf.read()) != -1)
    stream.write(readBytes);
} catch (IOException ioe) {
  throw new ServletException(ioe.getMessage());
} finally {
  if (stream != null)
    stream.close();
  if (buf != null)
    buf.close();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

doGet(request, response);
}
}