Playing with audio recording in Android
Required permissions.
Class variables for audio file path, MediaRecorder, MediaPlayer and permission request code.
private var audioFilePath: String? = null private var mediaRecorder: MediaRecorder? = null private var mediaPlayer: MediaPlayer? = null private val REQUEST_PERMISSION_CODE = 1000
Request audio and storage permissions.
if (ContextCompat.checkSelfPermission(activity, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(activity, RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(activity, arrayOf(WRITE_EXTERNAL_STORAGE, RECORD_AUDIO), REQUEST_PERMISSION_CODE) }
Handle permission request result.
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { REQUEST_PERMISSION_CODE -> { if (grantResults.isNotEmpty()) { val storagePermission = grantResults[0] == PackageManager.PERMISSION_GRANTED; val audioPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED; if (storagePermission && audioPermission) { Toast.makeText(activity, "Permission Granted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(activity,"Permission Denied",Toast.LENGTH_SHORT).show(); } } } } }
Create audio file path. For simplicity, starting from there, the following code are functional only, without any UI/Views involved. Each of the following code block can be in a function itself.
audioFilePath = "${Environment.getExternalStorageDirectory().absolutePath}/recorded-audio.3gp"
Start recording sounds.
mediaRecorder = MediaRecorder() mediaRecorder?.setAudioSource(MediaRecorder.AudioSource.MIC) mediaRecorder?.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP) mediaRecorder?.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB) mediaRecorder?.setOutputFile(audioFilePath) try { mediaRecorder?.prepare() mediaRecorder?.start() } catch (e: IllegalStateException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() }
Stop recording.
mediaRecorder?.stop()
Play the recorded sounds.
mediaPlayer = MediaPlayer() try { mediaPlayer?.setDataSource(audioFilePath) mediaPlayer?.prepare() } catch (e: IOException) { e.printStackTrace() } mediaPlayer?.start()
Stop playing the recorded sounds.
mediaPlayer?.stop() mediaPlayer?.release()
https://developer.android.com/reference/android/media/MediaRecorder.html
https://developer.android.com/reference/android/media/MediaPlayer.html
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts