柯安滨的历程

记录走在技术这条道路上的点点滴滴

实现录音AAC格式,并上传到服务器,然后下载播放。(包括服务器端代码)

这是以前写的一个录音Sample,现在发上来与大家分享。代码并不是全部自己写的,是拿别人的一个应用来改的。


工程下载地址:http://download.csdn.net/detail/keanbin/6661417


1、使用的三方库:

VoAACEncoder


2、录音部分:

public void startRecord() {
		if (!Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			Toast.makeText(MainActivity.this, "请插入SD卡!", Toast.LENGTH_SHORT)
					.show();
			return;
		}

		try {
			// mRecordFileName = Environment.getExternalStorageDirectory()
			// .toString()
			// + "/testAAC"
			// + System.currentTimeMillis()
			// + ".aac";

			mRecordFileName = Environment.getExternalStorageDirectory()
					.toString() + "/testAAC.aac";

			fos = new FileOutputStream(mRecordFileName);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		System.out.println("fos = " + fos);
		new Thread(new Runnable() {
			@Override
			public void run() {
				VoAACEncoder vo = new VoAACEncoder();
				vo.Init(SAMPLERATE, 16000, (short) 1, (short) 1);// 采样率:16000,bitRate:32k,声道数:1,编码:0.raw
				// 1.ADTS
				int min = AudioRecord.getMinBufferSize(SAMPLERATE,
						AudioFormat.CHANNEL_IN_MONO,
						AudioFormat.ENCODING_PCM_16BIT);
				if (min < 2048) {
					min = 2048;
				}
				byte[] tempBuffer = new byte[2048];
				recordInstance = new AudioRecord(MediaRecorder.AudioSource.MIC,
						SAMPLERATE, AudioFormat.CHANNEL_IN_MONO,
						AudioFormat.ENCODING_PCM_16BIT, min);
				recordInstance.startRecording();
				isStartRecord = true;
				while (isStartRecord) {
					int bufferRead = recordInstance.read(tempBuffer, 0, 2048);
					byte[] ret = vo.Enc(tempBuffer);
					if (bufferRead > 0) {
						System.out.println("ret:" + ret.length);
						try {
							fos.write(ret);
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
				recordInstance.stop();
				recordInstance.release();
				recordInstance = null;
				vo.Uninit();
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();

	}

3、上传文件部分

class MyClickListener implements OnTouchListener {
		public boolean onTouch(View v, MotionEvent event) {
			Log.i("keanbin", "event.getAction() = " + event.getAction());
			switch (event.getAction()) {
			case MotionEvent.ACTION_UP:
				setTalkBtnBackground(false);
				// TODO 正常放开,接下来一般做以下事情:发送录音文件到服务器
				if (isStartRecord) {
					// 停止录音
					stopRecord();

					Toast.makeText(MainActivity.this, "开始上传文件!",
							Toast.LENGTH_SHORT).show();
					// 上传文件
					HttpOperateUtil
							.uploadFile(URL_UPLOAD_FILE, mRecordFileName);
					Toast.makeText(MainActivity.this, "上传完文件!",
							Toast.LENGTH_SHORT).show();
				}
				break;

			case MotionEvent.ACTION_CANCEL:
				setTalkBtnBackground(false);
				// TODO 异常放开,接下来一般做以下事情:删除录音文件

				// 停止录音
				stopRecord();
				break;

			default:
				break;
			}
			return false;
		}

	}

使用的工具类:

HttpOperateUtil.java:

package com.example.test_voaacencoder.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Environment;
import android.util.Log;

public class HttpOperateUtil {

	public static boolean uploadFile(String uploadUrl, String srcPath) {
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "******";
		try {
			URL url = new URL(uploadUrl);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url
					.openConnection();
			// 设置每次传输的流大小,可以有效防止手机因为内存不足崩溃
			// 此方法用于在预先不知道内容长度时启用,没有进行内部缓冲的 HTTP 请求正文的流。
			httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K
			// 允许输入输出流
			httpURLConnection.setDoInput(true);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setUseCaches(false);
			// 使用POST方法
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			httpURLConnection.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);

			DataOutputStream dos = new DataOutputStream(
					httpURLConnection.getOutputStream());
			dos.writeBytes(twoHyphens + boundary + end);
			dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
					+ srcPath.substring(srcPath.lastIndexOf("/") + 1)
					+ "\""
					+ end);
			dos.writeBytes(end);

			// 上传文件内容
			FileInputStream fis = new FileInputStream(srcPath);
			byte[] buffer = new byte[8192]; // 8k
			int count = 0;
			// 读取文件
			while ((count = fis.read(buffer)) != -1) {
				dos.write(buffer, 0, count);
			}
			fis.close();

			dos.writeBytes(end);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
			dos.flush();

			// 服务器返回结果
			InputStream is = httpURLConnection.getInputStream();
			InputStreamReader isr = new InputStreamReader(is, "utf-8");
			BufferedReader br = new BufferedReader(isr);
			String result = br.readLine();

			// Toast.makeText(this, result, Toast.LENGTH_LONG).show();
			Log.i("uploadFile", "uploadFile result = " + result);

			try {
				dos.close();
			} catch (Exception e) {
				e.printStackTrace();
				// setTitle(e.getMessage());
			}
			is.close();

			return true;

		} catch (Exception e) {
			e.printStackTrace();
			// setTitle(e.getMessage());
		}

		return false;
	}

	public static String downLoadFile(String fileUrl, String fileName) {
		String fileDir = "";
		try {
			// 判断SD卡是否存在,并且是否具有读写权限
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				// 获得存储卡的路径
				String sdpath = Environment.getExternalStorageDirectory() + "/";
				String savePath = sdpath + "download";
				URL url = new URL(fileUrl);
				// 创建连接
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.connect();
				// 获取文件大小
				int contentLength = conn.getContentLength();
				// 创建输入流
				InputStream is = conn.getInputStream();

				File file = new File(savePath);
				// 判断文件目录是否存在
				if (!file.exists()) {
					file.mkdir();
				}
				File apkFile = new File(savePath, fileName);
				FileOutputStream fos = new FileOutputStream(apkFile);
				int count = 0;
				// 缓存
				byte buf[] = new byte[1024];
				// 写入到文件中
				do {
					int numread = is.read(buf);
					// count += numread;
					// // 计算进度条位置
					// mPercent = (int) (((float) count / contentLength) * 100);
					// // 更新进度
					// mHandler.sendEmptyMessage(DOWNLOAD_PERCENT);
					if (numread <= 0) {
						// 下载完成
						fileDir = savePath + "/" + fileName;
						// if (checkUpdateResult(apkFile)) {
						// // 下载成功
						//
						// } else {
						// // 下载失败
						// fos.close();
						// is.close();
						// // throw new RuntimeException("下载文件出错");
						// }
						break;
					}
					// 写入文件
					fos.write(buf, 0, numread);
				} while (true);// !mCancelUpdate);// 点击取消就停止下载.
				fos.close();
				is.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return fileDir;
	}
}

4、播放部分

public void startPlay() {
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				
				Looper.prepare();
				// TODO Auto-generated method stub
				String fileUrl = "http://192.168.1.147/upload/testAAC.aac";

				String fileName = HttpOperateUtil.downLoadFile(fileUrl,
						fileUrl.substring(fileUrl.lastIndexOf("/") + 1));

				Log.i("keanbin", "fileName = " + fileName); 
				File file = new File(fileName);

				if (!file.exists()) {
					Toast.makeText(MainActivity.this, "没有音乐文件!", Toast.LENGTH_SHORT)
							.show();
					return;
				}

				mMediaPlayer = MediaPlayer.create(MainActivity.this,
						Uri.parse(fileName));
				mMediaPlayer.setLooping(false);
				mMediaPlayer.start();
				
				Looper.loop();
			}
		}).start();

	}

5、服务器端代码:

receive_file.php:

 <?php  
    $target_path  = "./upload/";//接收文件目录  
    $target_path = $target_path . basename( $_FILES['uploadedfile']['name']);  
    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {  
       echo "The file ".  basename( $_FILES['uploadedfile']['name']). " has been uploaded";  
    }  else{  
       echo "There was an error uploading the file, please try again!" . $_FILES['uploadedfile']['error'];  
    }  
    ?>  

6、效果图


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/keanbin/article/details/17139109
个人分类: Android
想对作者说点什么? 我来说一句

h5 web录音并上传后端

2018年03月01日 47KB 下载

没有更多推荐了,返回首页

不良信息举报

实现录音AAC格式,并上传到服务器,然后下载播放。(包括服务器端代码)

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭