Mistelo
Mistelo

Reputation: 136

How to save recorded audio into internal storage android

I tried many times to save recorded audio to internal storage but I got exception

Caused by: java.io.FileNotFoundException: /data/user/0/sepahtan.sepahtan/files/sound/1653658919164.3gp: open failed: ENOENT (No such file or directory)

private fun getFileName(): String {
    val path = requireContext().filesDir.path
    val file = File(path,"sound")

    try {
        file.mkdirs()
    }catch (e:Exception){}

    return "$file/${System.currentTimeMillis()}.3gp"
}

This function giving me path and i put it into

mediaPlayer.setDataSource(getFileName())

I already studied all question about this title

Upvotes: 1

Views: 1772

Answers (1)

Yousef Kazemi
Yousef Kazemi

Reputation: 164

The function you need is actually like this:

fun saveRecordedAudio(inputStream: InputStream) {
    val outputStream: OutputStream = FileOutputStream(getFileName())

    val buffer = ByteArray(1024)
    var read: Int
    var total: Long = 0
    while (inputStream.read(buffer).also { read = it } != -1) {
        outputStream.write(buffer, 0, read)
        total += read.toLong()
    }
    
    inputStream.close()
    outputStream.close()
}

Before mediaPlayer.setDataSource(getFileName()), Actually you need to get inputStream of your recorded file and save it into internal storage using above function.

You can record the audio using AudioRecord API from the Android SDK package.

Note that saving to storage may be a challenge for different Android versions.

Upvotes: 1

Related Questions