Android录音及播放功能实现
16lz
2021-01-23
【Main.java】
package net.blogjava.mobile.record;import java.io.File;import android.app.Activity;import android.media.MediaPlayer;import android.media.MediaRecorder;import android.media.MediaPlayer.OnCompletionListener;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class Main extends Activity implements OnClickListener {private MediaPlayer mediaPlayer;private MediaRecorder mediaRecorder = new MediaRecorder();private File audioFile;@Overridepublic void onClick(View view) {try {String msg = "";switch (view.getId()) {case R.id.btnStart:mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);audioFile = File.createTempFile("record_", ".wav");Log.d("Main", audioFile.getAbsolutePath());mediaRecorder.setOutputFile(audioFile.getAbsolutePath());mediaRecorder.prepare();mediaRecorder.start();msg = "正在录音...";break;case R.id.btnStop:if (audioFile != null) {mediaRecorder.stop();}msg = "已经停止录音.";break;case R.id.btnPlay:if (audioFile != null) {mediaPlayer = new MediaPlayer();mediaPlayer.setDataSource(audioFile.getAbsolutePath());mediaPlayer.prepare();mediaPlayer.start();mediaPlayer.setOnCompletionListener(new OnCompletionListener() {@Overridepublic void onCompletion(MediaPlayer mp) {setTitle("录音播放完毕.");}});msg = "正在播放录音...";}break;}setTitle(msg);Toast.makeText(this, msg, Toast.LENGTH_LONG).show();} catch (Exception e) {setTitle(e.getMessage());}}@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);Button btnStart = (Button) findViewById(R.id.btnStart);Button btnStop = (Button) findViewById(R.id.btnStop);Button btnPlay = (Button) findViewById(R.id.btnPlay);btnStart.setOnClickListener(this);btnStop.setOnClickListener(this);btnPlay.setOnClickListener(this);}}
【main.xml】
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" > <Button android:id="@+id/btnStart" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="录音" /> <Button android:id="@+id/btnStop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="停止" /> <Button android:id="@+id/btnPlay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="播放" /></LinearLayout>
【注意清单文件别忘记加权限】
<uses-permission android:name="android.permission.RECORD_AUDIO" />
更多相关文章
- 获得root权限
- 清单文件Manifest中的android:name
- 【转】Android --权限大全
- Android android 6.0权限校验及版本兼容问题
- Android 读取一个已经安装的包的权限
- 在Android java代码中如何改变文件的权限
- Android 的权限级别小记
- android SystemClock设置系统时间需要system权限