首页 > 其他分享 >安卓开发录音机

安卓开发录音机

时间:2025-01-07 16:58:54浏览次数:3  
标签:mRecorder 安卓 private 开发 void new import android 录音机

依赖

dependencies {

    implementation ("androidx.appcompat:appcompat:1.6.1")
    implementation ("androidx.recyclerview:recyclerview:1.3.0")
    implementation ("com.karumi:dexter:6.2.3")
    
    implementation(libs.appcompat)
    implementation(libs.material)
    implementation(libs.activity)
    implementation(libs.constraintlayout)
    testImplementation(libs.junit)
    androidTestImplementation(libs.ext.junit)
    androidTestImplementation(libs.espresso.core)
}

权限

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

主代码

MainActivity.java

package com.example.audiorecorder;


import android.Manifest;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;


public class MainActivity extends AppCompatActivity {
    // 在 MainActivity 中定义一个 ArrayList 来存储音频文件 URI
    private ArrayList<Uri> audioFiles = new ArrayList<>();
    private AudioFileAdapter adapter;
    private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
    private MediaRecorder mRecorder = null;
    private Uri mAudioUri = null;
    private boolean isRecording = false;
    private Handler mHandler = new Handler();
    private Runnable mRunnable;
    private long startTime = 0;

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

        // 初始化 RecyclerView 和 Adapter
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new AudioFileAdapter(this, audioFiles);
        recyclerView.setAdapter(adapter);

        // 加载已存在的录音文件
        loadExistingAudioFiles();

        Button btnRecord = findViewById(R.id.btnRecord);
        TextView txtTime = findViewById(R.id.txtTime);

        requestPermissions();

        btnRecord.setOnClickListener(v -> toggleRecording(txtTime));

// 在 MainActivity 中添加如下代码:
Button btnHistory = findViewById(R.id.btnHistory);
btnHistory.setOnClickListener(v -> {
    Intent intent = new Intent(MainActivity.this, RecordingListActivity.class);
    startActivity(intent);
});

    }

    private void toggleRecording(TextView txtTime) {
        if (!isRecording) {
            startRecording(txtTime);
            isRecording = true;
        } else {
            stopRecording(txtTime);
            isRecording = false;
        }
    }

    private void startRecording(TextView txtTime) {
        if (mRecorder != null) {
            // 如果 mRecorder 已经存在,则先停止并释放它
            stopRecording(txtTime);
        }

        ContentValues values = new ContentValues();
        values.put(MediaStore.Audio.Media.TITLE, "My Recording");
        values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
        values.put(MediaStore.Audio.Media.DATE_ADDED, System.currentTimeMillis() / 1000);

        // Create a new file in the media store
        mAudioUri = getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
        ParcelFileDescriptor pfd = null;
        try {
            mRecorder = new MediaRecorder();
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

            // 使用 ParcelFileDescriptor 来设置输出文件
            // 使用 ParcelFileDescriptor 来设置输出文件
            pfd = getContentResolver().openFileDescriptor(mAudioUri, "rw");
            if (pfd == null) {
                throw new IOException("Failed to open file descriptor for output.");
            }
            mRecorder.setOutputFile(pfd.getFileDescriptor());

            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mRecorder.prepare();
            mRecorder.start();
            startTime = System.currentTimeMillis();
            updateTimer(txtTime);
            isRecording = true;
            ((Button)findViewById(R.id.btnRecord)).setText("结束录音");
            // 录音结束后的回调
            mAudioUri = getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);

            // 将新的录音文件添加到列表并更新 RecyclerView
            audioFiles.add(mAudioUri);
            adapter.notifyItemInserted(audioFiles.size() - 1);

        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常情况,例如通知用户无法开始录音
            if (mRecorder != null) {
                mRecorder.release();
                mRecorder = null;
            }
        } finally {
            if (pfd != null) {
                try {
                    pfd.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    private void loadExistingAudioFiles() {
        // 这里实现从数据库或文件系统加载已有录音文件的逻辑
        // 并将它们添加到 audioFiles 列表中
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (adapter != null) {
            adapter.releaseMediaPlayer();
        }
    }
    private void stopRecording(TextView txtTime) {
        if (mRecorder != null) {
            try {
                mRecorder.stop();
            } catch (IllegalStateException e) {
                // 忽略异常,因为可能是由于 mRecorder 没有正确启动造成的
                e.printStackTrace();
            }
            mRecorder.release();
            mRecorder = null;
            isRecording = false;
            ((Button)findViewById(R.id.btnRecord)).setText("开始录音");
            txtTime.setText("00:00:00");
            if (mRunnable != null) {
                mHandler.removeCallbacks(mRunnable);
            }
        }
    }

    private void updateTimer(final TextView txtTime) {
        mRunnable = () -> {
            long millis = System.currentTimeMillis() - startTime;
            String hms = convertMillisToHHMMSS(millis);
            txtTime.setText(hms);
            mHandler.postDelayed(mRunnable, 1000);
        };
        mHandler.postDelayed(mRunnable, 0);
    }

    private String convertMillisToHHMMSS(long millis) {
        return new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date(millis));
    }

    private void requestPermissions() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.RECORD_AUDIO},
                    REQUEST_RECORD_AUDIO_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_RECORD_AUDIO_PERMISSION && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission was granted.
        } else {
            // Permission denied.
        }
    }
}

AudioFileAdapter

package com.example.audiorecorder;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.io.IOException;
import java.util.ArrayList;

public class AudioFileAdapter extends RecyclerView.Adapter<AudioFileAdapter.AudioViewHolder> {

    private final Context context;
    private final ArrayList<Uri> audioFiles;
    private MediaPlayer mediaPlayer;

    public AudioFileAdapter(Context context, ArrayList<Uri> audioFiles) {
        this.context = context;
        this.audioFiles = audioFiles;
        this.mediaPlayer = new MediaPlayer();
    }

    @NonNull
    @Override
    public AudioViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_audio_file, parent, false);
        return new AudioViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull AudioViewHolder holder, int position) {
        Uri uri = audioFiles.get(position);
        // 假设 item_audio_file 包含一个 TextView 和 Button
        holder.textView.setText("Recording " + (position + 1));
        holder.button.setOnClickListener(v -> playAudio(uri));
    }

    private void playAudio(Uri uri) {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.reset();
        }
        try {
            mediaPlayer.setDataSource(context, uri);
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {
        return audioFiles.size();
    }

    static class AudioViewHolder extends RecyclerView.ViewHolder {
        TextView textView;
        Button button;

        AudioViewHolder(View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.text_view);
            button = itemView.findViewById(R.id.play_button);
        }
    }

    // Remember to release the MediaPlayer resources when not in use
    public void releaseMediaPlayer() {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}
RecordingListActivity
package com.example.audiorecorder;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;

public class RecordingListActivity extends AppCompatActivity {

    private AudioFileAdapter adapter;
    private ArrayList<Uri> audioFiles = new ArrayList<>();

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

        // Initialize RecyclerView and Adapter
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new AudioFileAdapter(this, audioFiles);
        recyclerView.setAdapter(adapter);

        // Load existing audio files
        loadExistingAudioFiles();
    }

    private void loadExistingAudioFiles() {
        // Implement logic to load existing recordings into audioFiles list
        // This might involve querying the media store or a database
    }
}

布局

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <!-- Button for navigating to the history of recordings -->
    <Button
        android:id="@+id/btnHistory"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="历史记录"
        app:layout_constraintBottom_toBottomOf="@+id/btnRecord"
        app:layout_constraintStart_toEndOf="@+id/btnRecord"
        android:layout_marginStart="33dp"/>

    <!-- RecyclerView for displaying list items (will be hidden in MainActivity) -->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintTop_toBottomOf="@+id/btnHistory"
        app:layout_constraintBottom_toTopOf="@+id/txtTime"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:visibility="gone" />

    <!-- TextView for displaying the recording time -->
    <TextView
        android:id="@+id/txtTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="00:00:00"
        android:textSize="24sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintVertical_bias="0.5"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_bias="0.5" />

    <!-- Button for starting/stopping recording -->
    <com.google.android.material.button.MaterialButton
        android:id="@+id/btnRecord"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="开始录音"
        android:backgroundTint="@android:color/holo_red_dark"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintVertical_bias="0.66"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintHorizontal_bias="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>

activity_recording_list.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <!-- RecyclerView for displaying list items -->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

item_audio_file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="8dp">

    <!-- TextView for displaying the name or number of the recording -->
    <TextView
        android:id="@+id/text_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Recording Name"
        android:textAppearance="?attr/textAppearanceListItem"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/play_button"
        app:layout_constraintHorizontal_chainStyle="spread_inside"/>

    <!-- Button for playing the recording -->
    <Button
        android:id="@+id/play_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="播放"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/text_view"/>

</androidx.constraintlayout.widget.ConstraintLayout>

我用的java语言 用的Android API level是35 自娱自乐 仅供参考 点击历史记录还看不到历史录音列表还在完善 

记得在AndroidManifest加上

 <category android:name="android.intent.category.LAUNCHER" />

标签:mRecorder,安卓,private,开发,void,new,import,android,录音机
From: https://blog.csdn.net/m0_68456185/article/details/144988570

相关文章

  • 安卓开发拍照录制项目二 录制
     第一步拍照在这里AndroidStudio拍照-CSDN博客 依赖dependencies{implementation("androidx.camera:camera-core:1.2.0")implementation("androidx.camera:camera-camera2:1.2.0")implementation("androidx.camera:camera-lifecycle:1.......
  • 充气泵方案设计与开发
    充气泵是一种常见的气体压缩设备,它可以将空气或其他气体压缩成高压气体,用于充气、输送、压缩等工业和生活领域。充气泵方案是通过内部马达的运转来工作。抽气时,连通器的阀门被大气的气压冲开,气体进入气筒,而向轮胎中打气时,阀门又被气筒内的气压关闭,气体就进入了轮胎中。......
  • Vulkan 开发(十三):Vulkan 帧缓冲区(FrameBuffer)
    Vulkan系列文章:1. 开篇,Vulkan概述2. Vulkan实例3. Vulkan物理设备4. Vulkan设备队列5. Vulkan逻辑设备6. Vulkan内存管理7. Vulkan缓存8. Vulkan图像9. Vulkan图像视图10. Vulkan窗口表面(Surface)11. Vulkan交换链12. Vulkan渲染通道V......
  • 商城开发需要用到的工具
    商城开发需要用到的工具主要包括后端语言、数据库系统、网页框架、前端技术和额外技术等。以下是关于这些工具的具体介绍:后端语言:后端语言是商城开发中不可或缺的一部分,它负责处理用户请求、连接数据库并生成动态内容。常用的后端语言有Java、Python和Ruby等。数据库系统:数据库......
  • SpringBoot农耕知识查询平台92fy3(程序+源码+数据库+调试部署+开发环境)
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表用户,植物种类,耕作准备,育种选择,作物生长,作物结果,作物收获开题报告内容一、研究背景与意义随着信息技术的飞速发展,各行各业都在积极探索数字化转型的路径。......
  • 《前端开发必看!React .tsx vs Vue .vue:深度对比,选型不再纠结!》
    .tsx与.vue的区别......
  • Docker 的基本概念和优势,以及在应用程序开发中的实际应用。
    Docker是一个开放源代码的容器化平台,用于轻松构建、打包和部署应用程序。它基于操作系统层面的虚拟化技术,通过创建容器来隔离应用程序的运行环境,使应用程序能够在不同的操作系统上运行,而无需担心依赖关系和环境差异。Docker的主要优势包括:简化应用程序的构建与部署:Docker......
  • 1688商品类目API接口的开发应用与收益
    在电子商务领域,数据的获取与分析是企业决策的关键。阿里巴巴旗下的1688平台,作为全球领先的B2B在线交易市场,提供了丰富的API接口,助力企业高效获取商品信息,优化供应链管理,提升市场竞争力。本文将深入探讨1688商品类目API接口的开发应用,结合实际案例,展示其为企业带来的显著收益,并......
  • 《鸿蒙开发-答案之书》将系统路径文件复制到沙盒工具类
    《鸿蒙开发-答案之书》将系统路径文件复制到沙盒工具类如果没有问存储权限,是不能访问系统文件的。但是可以把系统文件拷贝到你app的沙盒里面,就可以访问了。沙盒本质就是你app缓存的目录直接上代码:publicstaticasynccopyToSandbox(uris:Array<string>):Promise<Ar......
  • Mysql开发过程复杂操作
    Mysql开发过程复杂操作文章目录Mysql开发过程复杂操作Mysql开发过程复杂操作1-复杂操作总结1-【添加时】更新相同KEY2-【查询后】添加到库中3-【关联表】更新4-【批量】数据插入5-【批量】数据更新2-复杂操作案例1-【添加时】更新相同KEY示例解释:2-【添加时更新】DUPL......