android录音播放并上传

最近研究了下录音上传,各位有需要可参考下,如有不妥欢迎指出


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


  • 5
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在Android播放录音,你需要按照以下步骤进行操作: 1. 在你的AndroidManifest.xml文件中添加录音和存储权限: ``` <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> ``` 2. 首先,在你的代码中创建一个线程池来执行录音播放任务。你可以使用ThreadPoolExecutor类来创建线程池,并设置合适的参数,例如线程数量、线程池的工作队列等。下面是一个示例代码: ``` ThreadPoolExecutor mExecutorService = new ThreadPoolExecutor(3, 5, 1, TimeUnit.MINUTES, new LinkedBlockingDeque<>(10), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); ``` 3. 然后,使用AudioRecord类来录制音频数据。你可以在一个单独的线程中执行录音任务,以避免阻塞UI线程。在录音过程中,你可以将音频数据保存到文件中,以便后续播放。以下是录音的示例代码: ``` // 创建一个AudioRecord对象 AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, channelConfig, audioFormat, bufferSize); // 开始录音 audioRecord.startRecording(); // 读取录音数据并保存到文件中 byte[] buffer = new byte<span class="em">1</span><span class="em">2</span> #### 引用[.reference_title] - *1* [【安卓开发】Android实现录音播放功能](https://blog.csdn.net/weixin_45675097/article/details/121669958)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* [Android开发之PCM录音实时播放的实现方法 | 边录音播放 |PCM录音播放无延迟 | 录音无杂音 | 录音无噪音](https://blog.csdn.net/xiayiye5/article/details/122664083)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值