import android.Manifest
import android.content.pm.PackageManager
import android.media.MediaRecorder
import android.os.Bundle
import android.os.Environment
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.io.IOException
class AudioRecorderActivity : AppCompatActivity() {
private lateinit var mediaRecorder: MediaRecorder
private var isRecording = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_audio_recorder)
val recordButton = findViewById<Button>(R.id.record_button)
recordButton.setOnClickListener {
if (isRecording) {
stopRecording()
} else {
if (checkPermissions()) {
startRecording()
}
}
}
}
private fun startRecording() {
mediaRecorder = MediaRecorder()
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC)
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
val filePath = Environment.getExternalStorageDirectory().absolutePath + "/recording.3gp"
mediaRecorder.setOutputFile(filePath)
try {
mediaRecorder.prepare()
mediaRecorder.start()
isRecording = true
Toast.makeText(this, "Recording started", Toast.LENGTH_SHORT).show()
} catch (e: IOException) {
e.printStackTrace()
}
}
private fun stopRecording() {
mediaRecorder.stop()
mediaRecorder.release()
isRecording = false
Toast.makeText(this, "Recording stopped", Toast.LENGTH_SHORT).show()
}
private fun checkPermissions(): Boolean {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.RECORD_AUDIO), 1)
return false
}
return true
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == 1 && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startRecording()
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
}
}
}