Records audio and saves it to a folder Android kotlin Example

02-Jan-2025

Records audio and saves it to a folder Android kotlin Example

Output:



1/  Modify your AndroidManifest.xml



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.RecordsAudioAndSavesItToAFolder"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>



2/  Modify activity_main.xml



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="16dp">

<Button
android:id="@+id/btnRecord"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start Recording" />

<Button
android:id="@+id/btnPlay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Play Audio"
android:enabled="false" />
</LinearLayout>




3/  Modify MainActivity.kt



package com.zissofworks.recordsaudioandsavesittoafolder

import android.content.pm.PackageManager
import android.media.MediaPlayer
import android.media.MediaRecorder
import android.os.Bundle
import android.os.Environment
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.io.File
import java.io.IOException

class MainActivity : AppCompatActivity() {

private lateinit var btnRecord: Button
private lateinit var btnPlay: Button
private var mediaRecorder: MediaRecorder? = null
private var mediaPlayer: MediaPlayer? = null
private var isRecording = false
private var audioFilePath: String? = null
private val PERMISSION_REQ_CODE = 1001

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}

btnRecord = findViewById(R.id.btnRecord)
btnPlay = findViewById(R.id.btnPlay)

btnRecord.setOnClickListener {
if (isRecording) {
stopRecording()
} else {
if (checkPermissions()) {
startRecording()
} else {
requestPermissions()
}
}
}

btnPlay.setOnClickListener {
if (audioFilePath != null) {
playAudio()
} else {
Toast.makeText(this, "No audio file found to play!", Toast.LENGTH_SHORT).show()
}
}

}


private fun startRecording() {
val audioFolder = File(getExternalFilesDir(Environment.DIRECTORY_MUSIC), "MyAudio")
if (!audioFolder.exists()) {
audioFolder.mkdirs()
}

val audioFile = File(audioFolder, "audio_test.mp4")
audioFilePath = audioFile.absolutePath

mediaRecorder = MediaRecorder().apply {
setAudioSource(MediaRecorder.AudioSource.MIC)
setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
setOutputFile(audioFilePath)

try {
prepare()
start()
isRecording = true
btnRecord.text = "Stop Recording"
btnPlay.isEnabled = false
Toast.makeText(this@MainActivity, "Recording started!", Toast.LENGTH_SHORT).show()
} catch (e: IOException) {
e.printStackTrace()
Toast.makeText(this@MainActivity, "Failed to record audio", Toast.LENGTH_SHORT).show()
}
}
}

private fun stopRecording() {
mediaRecorder?.apply {
stop()
release()
}
mediaRecorder = null
isRecording = false
btnRecord.text = "Start Recording"
btnPlay.isEnabled = true
Toast.makeText(this, "Recording saved: $audioFilePath", Toast.LENGTH_LONG).show()
}

private fun playAudio() {
mediaPlayer = MediaPlayer().apply {
try {
setDataSource(audioFilePath)
prepare()
start()
Toast.makeText(this@MainActivity, "Playing audio...", Toast.LENGTH_SHORT).show()

setOnCompletionListener {
Toast.makeText(this@MainActivity, "Audio playback completed.", Toast.LENGTH_SHORT).show()
releaseMediaPlayer()
}
} catch (e: IOException) {
e.printStackTrace()
Toast.makeText(this@MainActivity, "Failed to play audio", Toast.LENGTH_SHORT).show()
}
}
}

private fun releaseMediaPlayer() {
mediaPlayer?.release()
mediaPlayer = null
}

private fun checkPermissions(): Boolean {
val recordPermission = ContextCompat.checkSelfPermission(this, android.Manifest.permission.RECORD_AUDIO)
val storagePermission = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
return recordPermission == PackageManager.PERMISSION_GRANTED &&
storagePermission == PackageManager.PERMISSION_GRANTED
}

private fun requestPermissions() {
ActivityCompat.requestPermissions(
this,
arrayOf(android.Manifest.permission.RECORD_AUDIO, android.Manifest.permission.WRITE_EXTERNAL_STORAGE),
PERMISSION_REQ_CODE
)
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == PERMISSION_REQ_CODE) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startRecording()
} else {
Toast.makeText(this, "Permissions denied", Toast.LENGTH_SHORT).show()
}
}
}

override fun onDestroy() {
super.onDestroy()
releaseMediaPlayer()
}
}



1/  Create A New Project .


Comments