我想从Android客户端发送音频文件.MP3文件与Servlet服务器,并将其保存在一个位置。如果我打在它应该发挥的位置保存.MP3文件。 我的问题是有没有办法直接从客户端的servlet发送一个.MP3文件服务器和检索MP3文件。
我的客户端code是如下:
包com.android.audiorecord;
进口的java.io.File;
进口java.io.IOException异常;
进口的java.util.ArrayList;
进口org.apache.commons.io.FileUtils;
进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.message.BasicNameValuePair;
进口com.android.audiofileplayer.StreamingMp3Player;
进口android.app.Activity;
进口android.content.Context;
进口android.content.Intent;
进口android.media.MediaPlayer;
进口android.media.MediaRecorder;
进口android.os.Bundle;
进口android.os.Environment;
进口android.util.Base64;
进口android.util.Log;
进口android.view.View;
进口android.view.ViewGroup;
进口android.widget.Button;
进口android.widget.LinearLayout;
公共类AudioRecordActivity扩展活动
{
私有静态最后弦乐LOG_TAG =AudioRecordTest;
私有静态字符串mFileName = NULL;
私人字符串URL =QRFileSaveServlet;
字符串结果;
byte []的价值;
字符串s;
byte []的filebyte,clientbyte;
字符串readString;
私人RecordButton mRecordButton = NULL;
私人MediaRecorder mRecorder = NULL;
私人提交按钮mSubmitButton = NULL;
私人PLAYBUTTON mPlayButton = NULL;
私人MediaPlayer的MPLAYER = NULL;
字符串fileresult =;
HTT presponse响应;
私人无效真实记录(布尔开始){
如果(开始){
的StartRecording();
} 其他 {
STO precording();
}
}
私人无效onPlay(布尔开始){
如果(开始){
startPlaying();
} 其他 {
stopPlaying();
}
}
私人无效startPlaying(){
MPLAYER =新的MediaPlayer();
尝试 {
mPlayer.setDataSource(mFileName);
MPLAYER prepare()。
mPlayer.start();
}赶上(IOException异常E){
Log.e(LOG_TAG,prepare()失败);
}
}
私人无效stopPlaying(){
mPlayer.release();
MPLAYER = NULL;
}
私人无效的startRecording(){
mRecorder =新MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEn codeR(MediaRecorder.AudioEn coder.AMR_NB);
尝试 {
mRecorder prepare()。
}赶上(IOException异常E){
Log.e(LOG_TAG,prepare()失败);
}
mRecorder.start();
}
/ *公共布尔另存为(INT ressound){
byte []的缓冲区= NULL;
InputStream的FIN = getBaseContext()getResources()openRawResource(ressound)。
INT大小= 0;
尝试 {
大小= fIn.available();
缓冲区=新的字节[尺寸]
fIn.read(缓冲液);
fIn.close();
}赶上(IOException异常E){
// TODO自动生成的catch块
返回false;
}
字符串路径=/ SD卡/媒体/音频/铃声/;
奥格字符串文件名=examplefile+;
布尔存在=(新文件(路径))存在();
如果(存在!){新的文件(路径).mkdirs();}
FileOutputStream中保存;
尝试 {
保存=新的FileOutputStream(路径+文件名);
save.write(缓冲液);
save.flush();
save.close();
}赶上(FileNotFoundException异常E){
// TODO自动生成的catch块
返回false;
}赶上(IOException异常E){
// TODO自动生成的catch块
返回false;
}
sendBroadcast(新意图(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.parse(文件://+路径+文件名)));
文件k =新的文件(路径,文件名);
ContentValues值=新ContentValues();
values.put(MediaStore.MediaColumns.DATA,k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLEexampletitle);
values.put(MediaStore.MediaColumns.MIME_TYPE,音频/ OGG);
values.put(MediaStore.Audio.Media.ARTISTcssounds);
values.put(MediaStore.Audio.Media.IS_RINGTONE,真正的);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION,真正的);
values.put(MediaStore.Audio.Media.IS_ALARM,真正的);
values.put(MediaStore.Audio.Media.IS_MUSIC,假);
//把它插入到数据库
。this.getContentResolver()插入(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()),值);
返回true;
} * /
私人无效STO precording(){
mRecorder.stop();
mRecorder.release();
// mRecorder.reset();
mRecorder = NULL;
}
类RecordButton扩展按钮{
布尔mStartRecording = TRUE;
OnClickListener唱首歌=新OnClickListener(){
公共无效的onClick(视图v){
真实记录(mStartRecording);
如果(mStartRecording){
的setText(停止录制);
} 其他 {
的setText(开始录音);
}
mStartRecording = mStartRecording!;
}
};
公共RecordButton(上下文CTX){
超(CTX);
的setText(开始录音);
setOnClickListener(唱首歌);
}
}
类PLAYBUTTON扩展按钮{
布尔mStartPlaying = TRUE;
OnClickListener唱首歌=新OnClickListener(){
公共无效的onClick(视图v){
onPlay(mStartPlaying);
如果(mStartPlaying){
的setText(停止播放);
} 其他 {
的setText(开始播放);
}
mStartPlaying = mStartPlaying!;
}
};
公共PLAYBUTTON(上下文CTX){
超(CTX);
的setText(开始播放);
setOnClickListener(唱首歌);
}
}
一流的提交按钮扩展按钮{
OnClickListener唱首歌=新OnClickListener(){
公共无效的onClick(视图v){
文件F =新的文件(Environment.getExternalStorageDirectory()+/ audiorecordtest.mp3);
//
// byte []的文件= fileresult.getBytes();
尝试 {
filebyte = FileUtils.readFileToByteArray(F);
}赶上(IOException异常E){
// TODO自动生成的catch块
e.printStackTrace();
}
的System.out.println($$$$$$$$$$$+ filebyte);
clientbyte = Base64.en code(filebyte,MODE_APPEND); //(filebyte,MODE_APPEND);
S =新的String(clientbyte);
的System.out.println(**************+ S);
ArrayList的<的NameValuePair> namevaluepairs中=新的ArrayList<的NameValuePair>();
nameValuePairs.add(新BasicNameValuePair(的AudioFile,S));
结果= AudioServer.executePost(URL,namevaluepairs中);
结果= result.trim();
的System.out.println(回应:收到+结果);
如果(结果!= NULL){
束束=新包();
意图explicitIntent =新的意图(AudioRecordActivity.this,
StreamingMp3Player.class);
bundle.putString(结果,结果);
explicitIntent.putExtras(包);
startActivity(explicitIntent);
}
}
};
公众提交按钮(上下文CTX){
超(CTX);
的setText(保存);
setOnClickListener(唱首歌);
}
}
公共AudioRecordActivity(){
mFileName = Environment.getExternalStorageDirectory()getAbsolutePath()。
mFileName + =/audiorecordtest.mp3;
}
@覆盖
公共无效的onCreate(包冰柱){
super.onCreate(冰柱);
的LinearLayout LL =新的LinearLayout(本);
mRecordButton =新RecordButton(本);
ll.addView(mRecordButton,
新LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mPlayButton =新PLAYBUTTON(本);
ll.addView(mPlayButton,
新LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mSubmitButton =新的提交按钮(这一点);
ll.addView(mSubmitButton,新LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,0));
的setContentView(Ⅱ);
}
@覆盖
公共无效的onPause(){
super.onPause();
如果(mRecorder!= NULL){
mRecorder.release();
mRecorder = NULL;
}
如果(MPLAYER!= NULL){
mPlayer.release();
MPLAYER = NULL;
}
}
}
在此我可以送audiorecordtest.mp3文件direcly到服务器,而无需编码为byte [],并在namevalue对发送。
我的服务器端code是如下:
包com.gsr.qrbar code;
进口java.io.BufferedInputStream中;
进口java.io.ByteArrayInputStream中;
进口的java.io.File;
进口java.io.FileInputStream中;
进口java.io.FileOutputStream中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口的java.io.PrintWriter;
进口java.net.MalformedURLException;
进口的java.net.URL;
进口com.android.gsr.utils.AudioSampleReader;
进口com.android.gsr.utils.AudioSampleWriter;
进口com.android.gsr.utils.Base64;
进口javax.servlet.ServletException;
进口javax.servlet.ServletOutputStream;
//进口javax.servlet.annotation.WebServlet;
进口javax.servlet.http.HttpServlet的;
进口javax.servlet.http.HttpServletRequest;
进口javax.servlet.http.HttpServletResponse;
进口javax.sound.sampled.AudioFileFormat;
进口javax.sound.sampled.AudioFileFormat.Type中;
进口javax.sound.sampled.AudioFormat中;
进口javax.sound.sampled.AudioInputStream中;
进口javax.sound.sampled.AudioSystem;
进口javax.sound.sampled.DataLine中;
进口javax.sound.sampled.LineUnavailableException;
进口javax.sound.sampled.SourceDataLine;
进口javax.sound.sampled.UnsupportedAudioFileException;
进口org.apache.commons.io.FileUtils;
/ **
* Servlet实现类QRFileSaveServlet
* /
// @ WebServlet(/ QRFileSaveServlet)
公共类QRFileSaveServlet延伸的HttpServlet {
私有静态最后长的serialVersionUID = 1L;
的AudioInputStream AIS;
/ **
*默认构造函数。
* /
公共QRFileSaveServlet(){
// TODO自动生成构造函数存根
}
/ **
* @see的HttpServlet#的doGet(HttpServletRequest的请求,HttpServletResponse的响应)
* /
保护无效的doGet(HttpServletRequest的请求,HttpServletResponse的响应)抛出了ServletException,IOException异常{
// TODO自动生成方法存根
}
/ **
* @see的HttpServlet#的doPost(HttpServletRequest的请求,HttpServletResponse的响应)
* /
保护无效的doPost(HttpServletRequest的请求,HttpServletResponse的响应)抛出了ServletException,IOException异常{
// TODO自动生成方法存根
字符串qrfile =的request.getParameter(AUDIOFILE);
的System.out.println(字符串参数\+ qrfile);
字节[]的AudioFile = Base64.de code(qrfile);
字符串中newstr =新的String(audiofile的);
//显示字节数组的内容。
的System.out.println(新的字符串等于\+中newstr +\);
。字符串文件路径= this.getServletContext()getRealPath(/)+;
的System.out.println(+文件路径的文件的路径);
字符串文件上传=AudioFileStorage;
// PrintWriter的输出= response.getWriter();
文件f;
F =新的文件(文件路径);
// INT状态= 0;
如果(f.exists()){
文件路径+ =文件上传;
F =新的文件(文件路径);
如果(!f.exists()){
f.mkdir();
}
F =新的文件(文件路径,请将test.mp3);
如果(!f.exists()){
FileOutputStream中FOS =新的FileOutputStream(F);
fos.write(audiofile的);
fos.flush();
fos.close();
} 其他 {
//out.println("failure);
ServletOutputStream的流= NULL;
的BufferedInputStream BUF = NULL;
尝试{
流= response.getOutputStream();
//文件MP3 =新的文件(mp3Dir +/+文件名);
response.setContentType(音频/ MPEG);
response.addHeader(内容处置,附件;文件名=+ F);
response.setContentLength((int)的f.length());
的FileInputStream输入=新的FileInputStream(F);
BUF =新的BufferedInputStream(输入);
INT的ReadBytes = 0;
而((的ReadBytes = buf.read())!= - 1)
stream.write(的ReadBytes);
的System.out.println(响应流+流);
}赶上(IOException异常IOE){
抛出新的ServletException异常(ioe.getMessage());
} 最后 {
如果(流!= NULL)
stream.close();
如果(BUF!= NULL)
buf.close();
}
}
}
如果(文件路径== NULL || filePath.equals())
抛出新的ServletException异常(
无效或者不存在的mp3Dir的context-param。);
网址URL = NULL;
尝试{
URL = f.toURL();
的System.out.println(URL:+网址);
的System.out.println(成功转换处理);
}
赶上(MalformedURLException的我){
的System.out.println(转换过程中的错误);
}
//串rfilepath = this.getServletContext()getRealPath(/)+AudioFileStorage /请将test.mp3。
在rfilepath+ rfilepath)的//System.out.println("Path;
}
}
在这里我可以直接拿到audiorecordtest.mp3文件从客户端,而在服务器端进行解码,并在这个servlet玩
客户端在本地我的服务器连接 executepost()如下:
包com.android.audio;
进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.net.URI中;
进口的java.util.ArrayList;
进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;
公共类AUDIOSERVER {
静态的InputStream是;
私有静态字符串API_URL =http://192.168.15.71:8088/QRBar$c$cServer/;
公共静态字符串executePost(字符串apiurl,
ArrayList的<的NameValuePair> urlParameters){
尝试 {
//创建连接
HttpClient的HttpClient的=新DefaultHttpClient();
HttpPost httppost =新HttpPost(API_URL + apiurl);
httppost.setEntity(新UrlEn codedFormEntity(urlParameters));
HTT presponse响应= httpclient.execute(httppost);
HttpEntity实体= response.getEntity();
是= entity.getContent();
//获取响应
// InputStream的是= connection.getInputStream();
的BufferedReader RD =新的BufferedReader(新InputStreamReader的(是));
串线;
StringBuffer的response1 =新的StringBuffer();
而((行= rd.readLine())!= NULL){
response1.append(线);
response1.append('\ r');
}
rd.close();
返回response1.toString();
}赶上(例外五){
e.printStackTrace();
返回null;
}
}
公共静态字符串executeHttpGet(字符串apiurl)抛出异常{
BufferedReader中的= NULL;
尝试 {
HttpClient的客户端=新DefaultHttpClient();
HTTPGET请求=新HTTPGET(API_URL + apiurl);
request.setURI(新的URI(apiurl));
HTT presponse响应= client.execute(要求);
在=新的BufferedReader(新的InputStreamReader(response.getEntity()
.getContent()));
StringBuffer的SB =新的StringBuffer();
串线=;
串NL = System.getProperty(line.separator);
而((行= in.readLine())!= NULL){
sb.append(行+ NL);
}
附寄();
字符串结果= sb.toString();
返回结果;
} 最后 {
如果(在!= NULL){
尝试 {
附寄();
}赶上(IOException异常E){
e.printStackTrace();
}
}
}
}
}
解决方案
下面是简单的方法来做到这一点。
1:从机器人侧读取MP3播放文件,并从中创建base64String。 2:在施维雅边读这base64String并将其转换回.MP3文件
任何文件转换为base64String以下是过程
档案文件=新的文件(Environment.getExternalStorageDirectory()+/hello-4.wav);
字节[]字节= FileUtils.readFileToByteArray(文件);
字符串连接codeD = Base64.en codeToString(字节,0);
I want to send an audio file .mp3 file from android client to servlet server and save it in a location. If I play that saved .mp3 file in that location it should play. My question is there a way to send a .mp3 file directly from client to server and retrieve that mp3 file in servlet.
My client side code is as follows:
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;
}
}
}
in this can i send audiorecordtest.mp3 file direcly to server without encoding to byte[] and send it in namevalue pair.
My server side code is as follows:
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);
}
}
here can i get that audiorecordtest.mp3 file directly from client without decoding in server side and play it in this servlet
my server connection in local for client executepost() is as follows:
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();
}
}
}
}
}
解决方案
here is simple way to do that
1: from android side read that .mp3 file and create base64String from it. 2: At servier side read this base64String and convert it back to .mp3 file.
to convert any file to base64String following is the process
File file = new File(Environment.getExternalStorageDirectory() + "/hello-4.wav");
byte[] bytes = FileUtils.readFileToByteArray(file);
String encoded = Base64.encodeToString(bytes, 0);