首页 > 其他分享 >MediaRecorder录音,MediaPlayer播放

MediaRecorder录音,MediaPlayer播放

时间:2023-04-06 21:36:52浏览次数:65  
标签:MediaRecorder MediaPlayer 录音 private new import mRecorder android conn


直接看代码

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

/**
 * http://blog.sina.com.cn/s/blog_68494364010116gk.html
 * @author reyo
 *
 */
public class AudioRecordActivty extends Activity{

	private static final String TAG = "AudioRecordActivty";
    private static String mFileName = null;
    private RecordButton mRecordButton = null;
    private PlayButton   mPlayButton = null;
    private MediaRecorder mRecorder = null;
    private MediaPlayer   mPlayer = null;
    
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        LinearLayout layout = new LinearLayout(this);
        mRecordButton = new RecordButton(this);
        layout.addView(mRecordButton,new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                0));
        mPlayButton = new PlayButton(this);
        layout.addView(mPlayButton,new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                0));
        setContentView(layout);
        
        mFileName = Environment.getExternalStorageDirectory().getPath();
        mFileName += "/audiorecordtest.amr";
        Log.i("tag", "mFileName="+mFileName);
        
    }
    
    @Override
    public void onPause() {
        super.onPause();
        stopRecording();
        stopPlaying();
    }
    
    private void onRecord(boolean start) {
        if (start) {
            startRecording();
        } else {
            stopRecording();
        }
    }
   
    private void startRecording() {
    	try {
	        mRecorder = new MediaRecorder();
	        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置麦克风
	        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);// 设置输出文件格式
	        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);// 设置编码格式
	        mRecorder.setOutputFile(mFileName);// 使用绝对路径进行保存文件
            mRecorder.prepare();
            mRecorder.start();
        } catch (IOException e) {
            Log.e(TAG, "prepare() failed");
        }
    }
    private void stopRecording() {
    	if(mRecorder!=null){
	        mRecorder.stop();
	        mRecorder.release();
	        mRecorder = null;
    	}
    }
    
    private void startPlaying() {
        try {
        	mPlayer = new MediaPlayer();
            mPlayer.setDataSource(mFileName);//获取绝对路径来播放音频
            mPlayer.prepare();
            mPlayer.start();
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
				
				@Override
				public void onCompletion(MediaPlayer mp) {
					// TODO Auto-generated method stub
					stopPlaying();
					mPlayButton.setEnabled(true);
				}
			});
            mPlayButton.setEnabled(false);
        } catch (IOException e) {
            Log.e(TAG, "prepare() failed");
        }
    }
    private void stopPlaying() {
    	if(mPlayer!=null){
                mPlayer.stop();
	        mPlayer.release();
	        mPlayer = null;
    	}
    }
    
    class RecordButton extends Button {
        boolean mStartRecording = true;
        public RecordButton(Context ctx) {
            super(ctx);
            setText("Start recording");
            setOnClickListener(clicker);
        }
        OnClickListener clicker = new OnClickListener() {
            public void onClick(View v) {
                onRecord(mStartRecording);
                if (mStartRecording) {
                    setText("Stop recording");
                } else {
                    setText("Start recording");
                }
                mStartRecording = !mStartRecording;
            }
        };
       
    }
    class PlayButton extends Button {
        public PlayButton(Context ctx) {
            super(ctx);
            setText("Start playing");
            setOnClickListener(clicker);
        }
        OnClickListener clicker = new OnClickListener() {
            public void onClick(View v) {
            	startPlaying();
            }
        };
        
    }
    
	class Fileter implements FilenameFilter {
		public boolean accept(File dir, String filename) {
			// TODO Auto-generated method stub
			return filename.equals(".amr");
		}
	}
    
	
	/**
     * 上传文件
     * @param urlStr 服务器地址
     * @param file 需要上传的文件
     * @return 上传是否成功
     */
    private boolean uploadFile(String urlStr,File file){
    	try {
    		String end = "\r\n";
    	    String hyphens = "--";
    	    String boundary = "*****";
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			/* 允许使用输入流,输出流,不允许使用缓存*/
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			/* 请求方式*/
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
			
			/* 当文件不为空,把文件包装并且上传*/
			Log.e(TAG, file.toString());
			if(file != null){
				DataOutputStream ds = new DataOutputStream(conn.getOutputStream());
				/* name里面的值为服务器端需要key   只有这个key 才可以得到对应的文件
				 * filename是文件的名字,包含后缀名的   比如:abc.png*/
				ds.writeBytes(hyphens + boundary + end);
				ds.writeBytes("Content-Disposition: form-data; " + "name=\"file1\";filename=\"" + 
						file.getName() +"\"" + end);
				ds.writeBytes(end);
				
				InputStream input = new FileInputStream(file);
				int size = 1024;
				byte[] buffer = new byte[size];
				int length = -1;
				/* 从文件读取数据至缓冲区*/
				while((length = input.read(buffer)) != -1){
					ds.write(buffer, 0, length);
				}
				input.close();
				ds.writeBytes(end);
				ds.writeBytes(hyphens + boundary + hyphens + end);
				ds.flush();
				
				/* 获取响应码*/
//				Log.e(TAG, "ResponseCode==="+conn.getResponseCode());
				if(conn.getResponseCode() == 200){
					return true;
				}
			}
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return false;
    }
    
}

标签:MediaRecorder,MediaPlayer,录音,private,new,import,mRecorder,android,conn
From: https://blog.51cto.com/u_5454003/6174165

相关文章