2011-12-22 125 views
-3

我在Android中录制了语音和格式为.mp3的音频文件,并使用base 64编码将其作为名称值对发送。现在,在我的服务器在我的servlet侧即我正的值,并使用基座64如何将byte []转换为servlet中的.mp4音频文件(webservice)

我的客户端代码它解码为字节[](机器人):

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

我的服务器端代码(在小服务程序):

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

       } 



} 

} 

wh在火腿在我的servlet做只是越来越byte [],并直接将其保存在一个文件的位置,但我想要的是在得到字节[]我想将其转换成.mp3音频文件并将其保存在一些路径..我不知道如何在获得byte []到.mp3音频文件之后继续执行此操作...任何一个plz都可以帮助我...

+0

没有不需要转换字节[]我只是想通过用request.getParameter获得并保存为MP3播放音频文件在我的服务器端并保存在一些路径位置 – pratibha 2011-12-22 06:19:22

+0

我的理解是,你的Android客户端确实发送和MP3文件。所以没有必要在您的服务器上将MP3转换成MP3!或者我错过任何东西? – home 2011-12-22 06:19:57

+0

然后我有一个疑问,当我从我的android客户端得到一个mp3文件作为字节[]时,我应该如何将它保存在我的服务器端作为.mp3文件。即我应该有例如在我的服务器端目的地中创建的“audiorecord.mp3”文件。当我点击那个应该在我的服务器端播放的.mp3文件。 – pratibha 2011-12-22 09:25:17

回答

0

如果您正在将MP4数据录制到文件,读取它,base64编码, base64解码,将字节写入文件,然后在目的地已经是MP4。你有错误吗?

+0

没有火腿没有得到任何错误...一个文本文件正在我的目的地创建,命名为“测试”,其中火腿有二进制值被保存 – pratibha 2011-12-22 09:14:12

+0

你是否正确的即时通讯在我的目的地获得mp4字节作为文本文件,但我什么想要实现的是我想播放音频和C,因为我应该有一个.mp4文件创建而不是文本文件,以便我可以播放该文件。例如在我的客户端一个.mp4音频文件正在SD卡中创建,就像它应该在我的服务器端目的地创建的 – pratibha 2011-12-22 09:34:17

+0

对不起pratibha,我不知道你的意思 – 2011-12-23 01:46:15

0

InputStream is = Context.openFileInput(someFileName); //不管你有什么formate

ByteArrayOutputStream bos = new ByteArrayOutputStream();

byte [] b = new byte [1024]; 而(!(INT bytesRead = is.read(B))= -1){

 bos.write(b, 0, bytesRead); 

}

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

使用audioDataString和中NameValuePair对象与发送该audioDataString