«

Android学习MediaRecorder和MediaPlayer

时间:2024-3-2 16:54     作者:韩俊     分类: Android


今天自己利用课余时间做了一个关于语音记录器的初步设计。主要实现的功能如下(录音、播放、发送音频):

(这是一个在客户端中使用的部分关键代码。MediaPlayer、MediaRecorder)

录音:

录音这里我使用到了MediaRecorder,这是一个语音保存的类,主要实现过程如下。

btRecord = (Button)findViewById(R.id.bt_record);
btRecord.setOnTouchListener(new Record());
class Record implements OnTouchListener{

        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                btRecord.setText(R.string.end_record);
                Toast.makeText(MainActivity.this, "开始录音", Toast.LENGTH_SHORT).show();
                mediaRecorder = new MediaRecorder();  
                mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);  
                mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);  
                mediaRecorder.setOutputFile(sFilePath);  
                mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);  
                try {  
                    mediaRecorder.prepare();  
                } catch (IOException e) {  
                    Log.e("Test : ", "prepare() failed");  
                }  
                mediaRecorder.start(); 

                break;
            case MotionEvent.ACTION_UP:
                btRecord.setText(R.string.start_record);
                Toast.makeText(MainActivity.this, "结束录音"+sFilePath, Toast.LENGTH_SHORT).show();
                file = new File(sFilePathInit, sFileName);
                mediaRecorder.stop();  
                mediaRecorder.release();  
                mediaRecorder = null; 
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
            default:
                break;
            }
            return true;
        }
    }


播放:

播放这里我使用到了MediaPlayer,这是一个语音播放的类,主要实现的过程如下。

btPlayer = (Button)findViewById(R.id.bt_play);
btPlayer.setOnTouchListener(new Player());
class Player implements OnTouchListener, OnCompletionListener{
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                btPlayer.setText(R.string.end_play);
                Toast.makeText(MainActivity.this, "开始播放", Toast.LENGTH_SHORT).show();
                mediaPlayer = new MediaPlayer();  
                try{  
                    mediaPlayer.setDataSource(sFilePath);  
                    mediaPlayer.prepare();  
                    mediaPlayer.start(); 
                    mediaPlayer.setOnCompletionListener(new Player());
                }catch(IOException e){  
                    Log.e("Test : ","播放失败");  
                }
                break;
            case MotionEvent.ACTION_UP:
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
            default:
                break;
            }
            return true;
        }

        //监听音频播放结束
        @Override
        public void onCompletion(MediaPlayer arg0)
        {
            btPlayer.setText(R.string.start_play);
            Toast.makeText(MainActivity.this, "结束播放", Toast.LENGTH_SHORT).show();
            mediaPlayer.release();  
            mediaPlayer = null; 
        }
    }

发送:

这里用到了服务器的连接,和音频的传输方面,具体的看代码就了解了。

public void uploadRecord(String filePath){

        String result = null;
        String  BOUNDARY =  UUID.randomUUID().toString();  //边界标识   随机生成
        String PREFIX = "--" , LINE_END = "rn"; 
        String CONTENT_TYPE = "multipart/form-data";   //内容类型

        try {
            URL url = new URL(URLDownload);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true);  //允许输入流
            conn.setDoOutput(true); //允许输出流
            conn.setUseCaches(false);  //不允许使用缓存
            conn.setRequestMethod("POST");  //请求方式
            conn.setRequestProperty("Charset", CHARSET);  //设置编码
            conn.setRequestProperty("connection", "keep-alive");   
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); 
            //conn.connect();
            if(file != null){

                /**
                 * 当文件不为空,把文件包装并且上传
                 */
                DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 这里重点注意:
                 * name里面的值为服务器端需要key   只有这个key 才可以得到对应的文件
                 * filename是文件的名字,包含后缀名的   比如:abc.png  
                 */

                sb.append("Content-Disposition: form-data; name="sound"; filename=""+file.getName()+"""+LINE_END); 
                sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(sFilePath);
                byte[] bytes = new byte[1024];
                int len = 0;
                while((len=is.read(bytes))!=-1)
                {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码  200=成功
                 * 当响应成功,获取响应的流  
                 */
                 int res = conn.getResponseCode();  
                Log.e(TAG, "response code:"+res);
                if(res==200)
                {
                    Log.e(TAG, "request success");
                    InputStream input =  conn.getInputStream();
                    StringBuffer sb1= new StringBuffer();
                    int ss ;
                    while((ss=input.read())!=-1)
                    {
                        sb1.append((char)ss);
                    }
                    result = sb1.toString();
                    Log.e(TAG, "result : "+ result);
                    //Toast.makeText(MainActivity.this, "上传成功!", Toast.LENGTH_LONG).show();
                }
                else{
                    Log.e(TAG, "request error");
                    //Toast.makeText(MainActivity.this, "上传失败!", Toast.LENGTH_LONG).show();
                }
                //showDialog(result);
                dos.close();
                conn.disconnect();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void showDialog(String mess){
        new AlertDialog.Builder(MainActivity.this).setTitle("Message").setMessage(mess).setNegativeButton("确定", new DialogInterface.OnClickListener()
        {

            @Override
            public void onClick(DialogInterface arg0, int arg1)
            {
                // TODO Auto-generated method stub

            }
        }).show();
    }

今天就写到这里,后面有时间了继续修改这篇博文。

sFilePath = Environment.getExternalStorageDirectory().getAbsolutePath(); //获取手机SD卡的路径。

需要添加的权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

晚安v_v

PS : 请尊重博主的劳动,如果需要转载,请注明出处。

标签: android

热门推荐