2011-12-22 95 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