MediaPlayer fails on prepare() with IOException

Viewed 76

I am creating a Soundboard application on Android in MVVM.

I am recording a sound through my application and want to replay it before definitely saving it.

Here's how I initialize my MediaRecorder in my Fragment

    /**
     * Define directory where audios will be saved
     * Set up media recorder
     */
    private fun initializeMediaRecorder() {
        output = activity?.getExternalFilesDir("TmpRecording").toString()

        mediaRecorder = MediaRecorder()

        mediaRecorder?.setAudioSource(MediaRecorder.AudioSource.DEFAULT)
        mediaRecorder?.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
        mediaRecorder?.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
        mediaRecorder?.setOutputFile("$output/$tmpRecordName.mp3")

    } 

Before replaying it, I can see in my storage that my file has been created. When I click on the repeat button, I am going through my ViewModel and using this code

    fun playRecord(record: Record?, source: String?, context: Context?) {
        mediaPlayer.reset()

        mediaPlayer.setAudioAttributes(
            AudioAttributes
                .Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .setLegacyStreamType(AudioManager.STREAM_MUSIC)
                .build()
        )

        if (null != record)
            mediaPlayer.setDataSource(record.source)
        else {
            val outputSource = context!!.getExternalFilesDir("TmpRecording").toString() + "/$source.mp3"
            mediaPlayer.setDataSource(outputSource)
        }

        try {
            mediaPlayer.prepare()
            mediaPlayer.start()
        } catch (e: IOException) {
            Toast.makeText(context, "Problem found IOException", Toast.LENGTH_SHORT).show()
            Log.e("XXX", e.message!!)
        } catch (ex: Exception) {
            Toast.makeText(context, "Problem found Exception", Toast.LENGTH_SHORT).show()
            Log.e("XXX", ex.message!!)
        }
    }

If I go through a Record object saved into DB and use the SAME method, it works. If I first record it then want to play it, I have an IOException on prepare() method.

I have already added in my Manifest.xml

android:usesCleartextTraffic="true"
android:networkSecurityConfig="@xml/network_security_config"

I have tried using prepareAsync() instead but nothing changes. Could anyone see my mistake(s) or help somehow please ?

0 Answers
Related