在 Android Studio 中做一个录音机APP
时间: 2023-11-10 21:11:34 浏览: 137
好的,下面是一个简单的录音机APP的实现步骤:
1. 在 Android Studio 中创建一个空白项目,并在布局文件中添加一个按钮和一个文本框用于显示录音时长。
2. 添加权限
在 AndroidManifest.xml 文件中添加以下权限:
```
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
3. 创建录音机类
创建一个名为 `SoundRecorder` 的 Java 类,该类用于管理录音的开始、停止、暂停和继续等操作。
```java
public class SoundRecorder {
private MediaRecorder mRecorder;
private String mFileName;
private long mStartTime;
public SoundRecorder(String fileName) {
mFileName = fileName;
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile(mFileName);
}
public void start() {
try {
mRecorder.prepare();
mRecorder.start();
mStartTime = System.currentTimeMillis();
} catch (IOException e) {
Log.e("SoundRecorder", "prepare() failed");
}
}
public void pause() {
mRecorder.pause();
}
public void resume() {
mRecorder.resume();
}
public void stop() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
public int getDuration() {
return (int) (System.currentTimeMillis() - mStartTime) / 1000;
}
}
```
4. 在 Activity 中调用录音机类
在 Activity 中创建一个 `SoundRecorder` 实例,并在按钮的点击事件中调用录音机的开始、停止、暂停和继续等方法,并在文本框中显示录音时长。
```java
public class MainActivity extends AppCompatActivity {
private Button mRecordButton;
private TextView mDurationTextView;
private SoundRecorder mRecorder;
private boolean mIsRecording = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecordButton = findViewById(R.id.record_button);
mDurationTextView = findViewById(R.id.duration_text_view);
mRecordButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mIsRecording) {
mRecorder.stop();
mIsRecording = false;
mRecordButton.setText("Record");
} else {
mRecorder = new SoundRecorder(getExternalCacheDir().getAbsolutePath() + "/recording.3gp");
mRecorder.start();
mIsRecording = true;
mRecordButton.setText("Stop");
new CountDownTimer(Long.MAX_VALUE, 1000) {
@Override
public void onTick(long millisUntilFinished) {
mDurationTextView.setText(String.format("%02d:%02d", mRecorder.getDuration() / 60, mRecorder.getDuration() % 60));
}
@Override
public void onFinish() {
}
}.start();
}
}
});
}
}
```
这样你就可以在 Android Studio 中创建一个简单的录音机APP了。
阅读全文