您的位置:首页 > 移动开发 > Android开发

android录音播放并上传

2016-04-07 22:53 507 查看
最近研究了下录音上传,各位有需要可参考下,如有不妥欢迎指出

<pre name="code" class="html">package com.kingtone.www.record;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Socket;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.kingtone.www.record.util.EnvironmentShare;

/**
* 本类主要实现 录音至SD卡上,并且可以实现录音的播放
*/
public class Main extends Activity implements OnClickListener {

// 多媒体播放器
private MediaPlayer mediaPlayer;
// 多媒体录制器
private MediaRecorder mediaRecorder = new MediaRecorder();
// 音频文件
private File audioFile;

// 传给Socket服务器端的上传和下载标志
private final int UP_LOAD = 1;
private final int DOWN_LOAD = 2;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 获得三个按钮的UI控件
Button btnStart = (Button) findViewById(R.id.btnStart);
Button btnStop = (Button) findViewById(R.id.btnStop);
Button btnPlay = (Button) findViewById(R.id.btnPlay);
Button btnUpLoad = (Button) findViewById(R.id.btnUpLoad);
Button btnDownLoad = (Button) findViewById(R.id.btnDownLoad);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
btnPlay.setOnClickListener(this);
btnUpLoad.setOnClickListener(this);
btnDownLoad.setOnClickListener(this);
}

@Override
public void onClick(View view) {
try {
String msg = "";
switch (view.getId()) {
// 开始录音
case R.id.btnStart:
if (!EnvironmentShare.haveSdCard()) {
Toast.makeText(this, "SD不存在,不正常录音!!", Toast.LENGTH_LONG).show();
} else {
// 设置音频来源(一般为麦克风)
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
// 设置音频输出格式(默认的输出格式)
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
// 设置音频编码方式(默认的编码方式)
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
// 创建一个临时的音频输出文件.record_是文件的前缀名 .amr是后缀名
audioFile = File.createTempFile("record_", ".amr", EnvironmentShare.getAudioRecordDir());
// audioFile =new
// File(Environment.getExternalStorageDirectory().getCanonicalPath()+"/sound.amr");
// 设置录制器的文件保留路径
mediaRecorder.setOutputFile(audioFile.getAbsolutePath());

// 准备并且开始启动录制器
mediaRecorder.prepare();
mediaRecorder.start();
msg = "正在录音...";
}
break;
// 停止录音
case R.id.btnStop:
if (audioFile != null && audioFile.exists()) {
// mediaRecorder.stop();
mediaRecorder.reset();
}
msg = "已经停止录音.";
break;
// 录音文件的播放
case R.id.btnPlay:

if (mediaRecorder != null) {
// mediaRecorder.stop();
mediaRecorder.reset();
}

if (audioFile != null && audioFile.exists()) {
Log.i("com.kingtone.www.record", ">>>>>>>>>" + audioFile);
mediaPlayer = new MediaPlayer();
// 为播放器设置数据文件
mediaPlayer.setDataSource(audioFile.getAbsolutePath());
// 准备并且启动播放器
mediaPlayer.prepare();
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
setTitle("录音播放完毕.");

}
});
msg = "正在播放录音...";
}
break;
// 上传录音文件
case R.id.btnUpLoad:
// 开始上传录音文件
if (audioFile != null) {
msg = "正在上传录音文件...";
audioUpLoad();
}
break;
// 下载录音文件
case R.id.btnDownLoad:
// 开始下载录音文件
msg = "正在下载录音文件...";
downLoadDFile();
break;
}
// 更新标题栏 并用 Toast弹出信息提示用户
if (!msg.equals("")) {
setTitle(msg);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
setTitle(e.getMessage());
}

}

@Override
protected void onDestroy() {
super.onDestroy();

if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();

}
if (mediaRecorder != null) {
//			mediaRecorder.reset();

mediaRecorder.release();
mediaRecorder=null;
}
}

/**
* 上传 录音文件
*/
private void audioUpLoad() {
new Thread() {
public void run() {
// DataInputStream reader = null;
// DataOutputStream out = null;
// Socket socket = null;
// byte[] buf = null;
// try {
// // 连接Socket
// socket = new Socket("192.168.42.219", 9999);
// // 1. 读取文件输入流
// reader = new DataInputStream(new BufferedInputStream(new
// FileInputStream(audioFile)));
// // 2. 将文件内容写到Socket的输出流中
// out = new DataOutputStream(socket.getOutputStream());
// out.writeInt(UP_LOAD);
// out.writeUTF(audioFile.getName()); // 附带文件名
//
// int bufferSize = 2048; // 2K
// buf = new byte[bufferSize];
// int read = 0;
// // 将文件输入流 循环 读入 Socket的输出流中
// while ((read = reader.read(buf)) != -1) {
// out.write(buf, 0, read);
// }
// handler.sendEmptyMessage(UPLOAD_SUCCESS);
// } catch (Exception e) {
// handler.sendEmptyMessage(UPLOAD_FAIL);
// } finally {
// try {
// // 善后处理
// buf = null;
// out.close();
// reader.close();
// socket.close();
// } catch (Exception e) {
//
// }
// }

// post请求上传
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost:8080/action.jsp");
FileBody fileBody = new FileBody(audioFile);
try {
StringBody stringBody = new StringBody("文件的描述");
MultipartEntity entity = new MultipartEntity();
entity.addPart("file", fileBody);
entity.addPart("desc", stringBody);
post.setEntity(entity);
HttpResponse response = httpclient.execute(post);
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {

HttpEntity entitys = response.getEntity();
if (entity != null) {
System.out.println(entity.getContentLength());
System.out.println(EntityUtils.toString(entitys));
}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();

};
}.start();

}

/**
* 下载录音文件
*/
private void downLoadDFile() {
new Thread() {
public void run() {
DataOutputStream writer = null;
DataOutputStream socketOut = null;

DataInputStream inPutStream = null;
Socket socket = null;
byte[] buf = null;
try {
// 连接Socket
socket = new Socket("192.168.42.219", 9999);
// 向服务端发送请求及数据
socketOut = new DataOutputStream(socket.getOutputStream());
socketOut.writeInt(DOWN_LOAD);
socketOut.writeUTF(audioFile.getName());

// 1. 读取Socket的输入流
inPutStream = new DataInputStream(socket.getInputStream());
File downLoadFile = new File(
EnvironmentShare.getDownAudioRecordDir().getAbsolutePath() + "/" + audioFile.getName());
downLoadFile.createNewFile();
// File downLoadFile = File.createTempFile( fileName,
// ".amr", EnvironmentShare.getDownAudioRecordDir());
// 2. 获得文件的输出流
writer = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(downLoadFile)));

int bufferSize = 2048; // 2K
buf = new byte[bufferSize];
int read = 0;
// 将文件输入流 循环 读入 Socket的输出流中
while ((read = inPutStream.read(buf)) != -1) {
writer.write(buf, 0, read);
}
handler.sendEmptyMessage(DOWNLOAD_SUCCESS);
} catch (Exception e) {
handler.sendEmptyMessage(DOWNLOAD_FAIL);
} finally {
try {
// 善后处理
buf = null;
inPutStream.close();
writer.close();
socket.close();
} catch (Exception e) {

}
}
};
}.start();

}

// Socket上传下载 结果标志
private final int UPLOAD_SUCCESS = 1;
private final int UPLOAD_FAIL = 2;
private final int DOWNLOAD_SUCCESS = 3;
private final int DOWNLOAD_FAIL = 4;

// Socket 上传下载 结果 Handler处理类
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
String showMessage = "";
switch (msg.what) {
case UPLOAD_SUCCESS:
showMessage = "录音文件上传成功!";
break;
case UPLOAD_FAIL:
showMessage = "录音文件上传失败!";
break;
case DOWNLOAD_SUCCESS:
showMessage = "录音文件下载成功!";
break;
case DOWNLOAD_FAIL:
showMessage = "录音文件下载失败!";
break;

default:
break;
}
// 显示提示信息并 设置标题
EnvironmentShare.showToastAndTitle(Main.this, showMessage, true);
};
};

}




package com.kingtone.www.record.util;

import java.io.File;

import android.app.Activity;
import android.os.Environment;
import android.widget.Toast;

/**
*
*
*  该类为 硬件检测的 公共类
*/
public class EnvironmentShare {

// 存放录音文件夹的名称
static String AUDIO_RECORD = "/AudioRecord";
// 存放下载而来的录音文件夹名称
static String DOWNLOAD_AUDIO_RECORD = "/AudioRecord/downLoad";

/**
*  检测当前设备SD是否可用
*
* @return  返回"true"表示可用,否则不可用
*/
public static boolean haveSdCard(){
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ;
}

/**
*  获得SD卡根目录路径
*
* @return String类型  SD卡根目录路径
*/
public static String getSdCardAbsolutePath(){
return Environment.getExternalStorageDirectory().getAbsolutePath();
}

/**
* 获得存储 录音文件的文件夹
*
* @return File类型
* 存储 录音文件的文件夹 .AUDIO_RECORD是一个文件夹
*/
public static File getAudioRecordDir(){
//把String再转换为一个file对象
File audioRecordFile = new File(EnvironmentShare.getSdCardAbsolutePath() + AUDIO_RECORD);
if (!audioRecordFile.exists()) {
// 此处可能会创建失败,暂不考虑
audioRecordFile.mkdir();
}
return audioRecordFile;
}

/**
* 获得存储 下载而来的录音文件的文件夹
*
* @return File类型
*         存储 下载而来的 录音文件的文件夹
*/
public static File getDownAudioRecordDir(){
File audioRecordFile = new File(EnvironmentShare.getSdCardAbsolutePath() + DOWNLOAD_AUDIO_RECORD);
if (!audioRecordFile.exists()) {
// 此处可能会创建失败,暂不考虑
audioRecordFile.mkdir();
}
return audioRecordFile;
}

/**
*  用Toast显示指定信息
*
* @param activity   Activity类型       要显示提示信息的页面上下文
* @param message    String类型            将显示的提示信息内容
* @param isLong     boolean类型         如果为"true"表示长时间显示,否则为短时间显示
*/
public static void showToast(Activity activity,String message,boolean isLong){
if (message == null ||message.equals(""))
return ;
int showTime = Toast.LENGTH_SHORT;
if (isLong) {
showTime = Toast.LENGTH_LONG;
}

Toast.makeText(activity, message, showTime).show();
}

/**
*  用Toast显示指定信息 并设置标题显示 信息
*
* @param activity   Activity类型       要显示提示信息的页面上下文
* @param message    String类型            将显示的提示信息内容
* @param isLong     boolean类型         如果为"true"表示长时间显示,否则为短时间显示
*/
public static void showToastAndTitle(Activity activity,String message,boolean isLong){
activity.setTitle(message);
showToast(activity, message, isLong);
}

}


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.titletest.MainActivity" >

<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

<Button
android:id="@+id/btn1"
android:layout_marginTop="15dp"
android:layout_below="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

</RelativeLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: