依赖
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