android 简单实现录音功能

  1. 一.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="vertical"
    android:padding="16dp">

    <!-- 显示数字 "1" 的 TextView -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="1"
        android:textSize="24sp"
        android:gravity="center"
        android:paddingBottom="16dp"/>

    <!-- 开始录音按钮 -->
    <Button
        android:id="@+id/startRecord"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="开始录音"
        android:textSize="18sp"
        android:padding="12dp"
        android:layout_marginBottom="8dp"/>

    <!-- 停止录音按钮 -->
    <Button
        android:id="@+id/stopRecord"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="停止录音"
        android:textSize="18sp"
        android:padding="12dp"
        android:layout_marginBottom="8dp"/>

    <!-- 开始播放按钮 -->
    <Button
        android:id="@+id/startPlay"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="开始播放"
        android:textSize="18sp"
        android:padding="12dp"
        android:layout_marginBottom="8dp"/>

    <!-- 停止播放按钮 -->
    <Button
        android:id="@+id/stopPlay"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="停止播放"
        android:textSize="18sp"
        android:padding="12dp"
        android:layout_marginBottom="8dp"/>

</LinearLayout>
  1. 2.对应的java页面
复制代码
public class MainActivity extends AppCompatActivity {

    private static final String LOG_TAG = "MainActivity";
    // 语音文件保存路径
    private String FileName = null;

    // 界面控件
    private Button startRecord;
    private Button startPlay;
    private Button stopRecord;
    private Button stopPlay;

    // 语音操作对象
    private MediaPlayer mPlayer = null;
    private MediaRecorder mRecorder = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化控件
        startRecord = findViewById(R.id.startRecord);
        startPlay = findViewById(R.id.startPlay);
        stopRecord = findViewById(R.id.stopRecord);
        stopPlay = findViewById(R.id.stopPlay);

        // 设置按钮监听器
        startRecord.setOnClickListener(new startRecordListener());
        stopRecord.setOnClickListener(new stopRecordListener());
        startPlay.setOnClickListener(new startPlayListener());
        stopPlay.setOnClickListener(new stopPlayListener());

        // 设置语音文件保存路径
        FileName = getExternalFilesDir(Environment.DIRECTORY_MUSIC).getAbsolutePath() + "/audiorecordtest.3gp";

        // 请求权限
        requestPermissions();
    }

    // 请求录音和存储权限
    private void requestPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    1);
        }
    }

    // 开始录音
    class startRecordListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // 检查权限
            if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                Log.e(LOG_TAG, "没有录音权限!");
                return;
            }

            mRecorder = new MediaRecorder();
            try {
                mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                mRecorder.setOutputFile(FileName);
                mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                mRecorder.prepare();
                mRecorder.start();
            } catch (IOException e) {
                Log.e(LOG_TAG, "录音准备或启动失败:" + e.getMessage());
            }
        }
    }

    // 停止录音
    class stopRecordListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (mRecorder != null) {
                try {
                    mRecorder.stop();
                } catch (RuntimeException e) {
                    Log.e(LOG_TAG, "停止录音失败:" + e.getMessage());
                } finally {
                    mRecorder.release();
                    mRecorder = null;
                }
            }
        }
    }

    // 开始播放
    class startPlayListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            mPlayer = new MediaPlayer();
            try {
                mPlayer.setDataSource(FileName);
                mPlayer.prepare();
                mPlayer.start();
            } catch (IOException e) {
                Log.e(LOG_TAG, "播放失败:" + e.getMessage());
            }
        }
    }

    // 停止播放
    class stopPlayListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (mPlayer != null) {
                mPlayer.release();
                mPlayer = null;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d(LOG_TAG, "权限已授予");
            } else {
                Log.e(LOG_TAG, "权限被拒绝");
            }
        }
    }
}最后不要忘记加对应的请求权限
相关推荐
teacher伟大光荣且正确43 分钟前
Qt Creator 配置 Android 编译环境
android·开发语言·qt
飞猿_SIR3 小时前
Android Exoplayer 实现多个音视频文件混合播放以及音轨切换
android·音视频
HumoChen994 小时前
GZip+Base64压缩字符串在ios上解压报错问题解决(安卓、PC模拟器正常)
android·小程序·uniapp·base64·gzip
沙振宇8 小时前
【HarmonyOS】ArkTS开发应用的横竖屏切换
android·华为·harmonyos
橙子199110169 小时前
Kotlin 中的作用域函数
android·开发语言·kotlin
zimoyin9 小时前
Kotlin 懒初始化值
android·开发语言·kotlin
枣伊吕波10 小时前
第六节第二部分:抽象类的应用-模板方法设计模式
android·java·设计模式
萧然CS10 小时前
使用ADB命令操作Android的apk/aab包
android·adb
_extraordinary_14 小时前
MySQL 事务(二)
android·数据库·mysql
鸿蒙布道师18 小时前
鸿蒙NEXT开发动画案例5
android·ios·华为·harmonyos·鸿蒙系统·arkui·huawei