做了一个测试系统录音权限的app,也算是一个简单版的录音机吧,实现了录音和播放功能,代码已经整理好。
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/prgress_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="40sp"
android:textStyle="bold"
android:text="0"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
/>
<Button
android:id="@+id/StartRecordAndSave_btn"
android:text="StartRecordAndSave"
android:textSize="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
/>
<Button
android:id="@+id/PlayRecordAudio_btn"
android:text="PlayRecordAudio"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
/>
</LinearLayout>
activity_permissions.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PermissionsActivity">
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.example.myapplication;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity implements MediaPlayer.OnCompletionListener,MediaPlayer.OnPreparedListener {
private static final int REQUEST_CODE = 0; // 请求码
// 所需的全部权限
static final String[] PERMISSIONS = new String[]{
//Manifest.permission.RECORD_AUDIO,
Manifest.permission.RECORD_AUDIO,
//Manifest.permission.MODIFY_AUDIO_SETTINGS,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
protected Toolbar mTToolbar;
private PermissionsChecker mPermissionsChecker; // 权限检测器
private MediaPlayer mediaPlayer;
private boolean isRecording = false;
private TextView mTv_progress3;
Button btn_three_play, btn_three_recorder;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPermissionsChecker = new PermissionsChecker(this);
btn_three_play = (Button) findViewById(R.id.PlayRecordAudio_btn);
btn_three_recorder = (Button) findViewById(R.id.StartRecordAndSave_btn);
mTv_progress3 = (TextView) findViewById(R.id.prgress_text);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
btn_three_play.setEnabled(false);
if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
startPermissionsActivity();
}
btn_three_play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
playRecorder();
}
});
btn_three_recorder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
recorder_Audio(); //audio权限获得
btn_three_play.setEnabled(true);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
@Override
protected void onResume() {
super.onResume();
// 缺少权限时, 进入权限配置页面
if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
startPermissionsActivity();
}
}
private void startPermissionsActivity() {
PermissionsActivity.startActivityForResult(this, REQUEST_CODE, PERMISSIONS);
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// 拒绝时, 关闭页面, 缺少主要权限, 无法运行
if (requestCode == REQUEST_CODE && resultCode == PermissionsActivity.PERMISSIONS_DENIED) {
finish();
}
}
private boolean isPlaying = false;
private int frequency = 11025;
int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
int audiosource = MediaRecorder.AudioSource.MIC;
int channelConfig = AudioFormat.CHANNEL_CONFIGURATION_MONO;
File recordingFile = null;
MainActivity.RecordAudio recordAudio = null;
MainActivity.PlayAudio playAudio = null;
@RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public void recorder_Audio() throws IOException {
//AudioRecord不会直接保存音频,需要自己保存
Log.d("file","begin");
File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
path.mkdirs();
try {
recordingFile = File.createTempFile("recording", ".pcm", path); //权限获得
} catch (IOException e) {
e.printStackTrace();
}
Log.d("file","end");
recordAudio = new MainActivity.RecordAudio();
recordAudio.execute();
}
public void playRecorder() {
isRecording = false;
playAudio = new MainActivity.PlayAudio();
playAudio.execute();
}
public void onCompletion(MediaPlayer mp) {
}
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
private class PlayAudio extends AsyncTask<Void, Integer, Void> {
@Override
protected Void doInBackground(Void... params) {
isPlaying = true;
int bufferSize = AudioTrack.getMinBufferSize(frequency, channelConfig, audioFormat);
short[] buffer = new short[bufferSize / 4];
DataInputStream dis = null;
try {
dis = new DataInputStream(new BufferedInputStream(new FileInputStream(recordingFile)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, frequency, channelConfig, audioFormat, bufferSize, AudioTrack.MODE_STREAM);
audioTrack.play();
try {
while (isPlaying && dis.available() > 0) {
int i = 0;
while (dis.available() > 0 && i < buffer.length) {
buffer[i] = dis.readShort();
i++;
}
audioTrack.write(buffer, 0, buffer.length);
}
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this, "语音开始播放", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(MainActivity.this, "语音播放完了", Toast.LENGTH_SHORT).show();
}
}
private class RecordAudio extends AsyncTask<Void, Integer, Void> {
@Override
protected Void doInBackground(Void... params) {
isRecording = true;
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(recordingFile)));
int bufferSize = AudioRecord.getMinBufferSize(frequency, channelConfig, audioFormat);
AudioRecord audioRecord = new AudioRecord(audiosource, frequency, channelConfig, audioFormat, bufferSize);
short[] buffer = new short[bufferSize];
audioRecord.startRecording();
int r = 0;
while (isRecording) {
int bufferReadResult = audioRecord.read(buffer, 0, bufferSize);
for (int i = 0; i < bufferReadResult; i++) {
try {
dos.writeShort(buffer[i]);
} catch (IOException e) {
e.printStackTrace();
}
}
publishProgress(new Integer(r));
r++;
}
audioRecord.stop();
dos.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this, "正在录音", Toast.LENGTH_SHORT).show();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mTv_progress3.setText(values[0] + "");
}
}}
permissionsActivity.java
package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
public class PermissionsActivity extends AppCompatActivity {
public static final int PERMISSIONS_GRANTED = 0; // 权限授权
public static final int PERMISSIONS_DENIED = 1; // 权限拒绝
private static final int PERMISSION_REQUEST_CODE = 0; // 系统权限管理页面的参数
private static final String EXTRA_PERMISSIONS =
"me.chunyu.clwang.permission.extra_permission"; // 权限参数
private static final String PACKAGE_URL_SCHEME = "package:"; // 方案
private PermissionsChecker mChecker; // 权限检测器
private boolean isRequireCheck; // 是否需要系统权限检测
// 启动当前权限页面的公开接口
public static void startActivityForResult(Activity activity, int requestCode, String... permissions) {
Intent intent = new Intent(activity, PermissionsActivity.class);
intent.putExtra(EXTRA_PERMISSIONS, permissions);
ActivityCompat.startActivityForResult(activity, intent, requestCode, null);
}
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent() == null || !getIntent().hasExtra(EXTRA_PERMISSIONS)) {
throw new RuntimeException("PermissionsActivity需要使用静态startActivityForResult方法启动!");
}
setContentView(R.layout.activity_permissions);
mChecker = new PermissionsChecker(this);
isRequireCheck = true;
}
@Override protected void onResume() {
super.onResume();
if (isRequireCheck) {
String[] permissions = getPermissions();
if (mChecker.lacksPermissions(permissions)) {
requestPermissions(permissions); // 请求权限
} else {
allPermissionsGranted(); // 全部权限都已获取
}
} else {
isRequireCheck = true;
}
}
// 返回传递的权限参数
private String[] getPermissions() {
return getIntent().getStringArrayExtra(EXTRA_PERMISSIONS);
}
// 请求权限兼容低版本
private void requestPermissions(String... permissions) {
ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
}
// 全部权限均已获取
private void allPermissionsGranted() {
setResult(PERMISSIONS_GRANTED);
finish();
}
/**
* 用户权限处理,
* 如果全部获取, 则直接过.
* 如果权限缺失, 则提示Dialog.
*
* @param requestCode 请求码
* @param permissions 权限
* @param grantResults 结果
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE && hasAllPermissionsGranted(grantResults)) {
isRequireCheck = true;
allPermissionsGranted();
} else {
isRequireCheck = false;
showMissingPermissionDialog();
}
}
// 含有全部的权限
private boolean hasAllPermissionsGranted(@NonNull int[] grantResults) {
for (int grantResult : grantResults) {
if (grantResult == PackageManager.PERMISSION_DENIED) {
return false;
}
}
return true;
}
// 显示缺失权限提示
private void showMissingPermissionDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(PermissionsActivity.this);
builder.setTitle("R.string.help");
builder.setMessage("R.string.string_help_text");
// 拒绝, 退出应用
builder.setNegativeButton("R.string.quit", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
setResult(PERMISSIONS_DENIED);
finish();
}
});
builder.setPositiveButton("R.string.settings", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
startAppSettings();
}
});
builder.show();
}
// 启动应用的设置
private void startAppSettings() {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse(PACKAGE_URL_SCHEME + getPackageName()));
startActivity(intent);
}
}
permissionsChecker.java
package com.example.myapplication;
import android.content.Context;
import android.content.pm.PackageManager;
import androidx.core.content.ContextCompat;
public class PermissionsChecker {
private final Context mContext;
public PermissionsChecker(Context context) {
mContext = context.getApplicationContext();
}
// 判断权限集合
public boolean lacksPermissions(String... permissions) {
for (String permission : permissions) {
if (lacksPermission(permission)) {
return true;
}
}
return false;
}
// 判断是否缺少权限
private boolean lacksPermission(String permission) {
return ContextCompat.checkSelfPermission(mContext, permission) ==
PackageManager.PERMISSION_DENIED;
}
}
|