1

So this is the simple code I use to play an audio file in my app:

    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {
        mediaPlayer.setDataSource(url);
        mediaPlayer.prepare();
        mediaPlayer.start();
    } catch (IOException e) {
        e.printStackTrace();
    }

And here is the error log:

java.io.IOException: Prepare failed
at android.media.MediaPlayer._prepare(Native Method)

This error makes the app freeze for like 10 seconds and happens when the url providing the mp3 file returns 404 (not found). So how can I solve the issue?

I have used mediaPlayer.prepareAsync(), but nothing changed.

SSP
  • 431
  • 4
  • 16

2 Answers2

0

You can try below method: https://developer.android.com/reference/android/media/MediaPlayer#setAudioStreamType(int)

the method, setAudioStreamType, was deprecated in API level 26.
use setAudioAttributes(android.media.AudioAttributes)
Alonso
  • 63
  • 6
0

Please try the below way, the below code is in kotlin but you can use this way in java

mPlayer = MediaPlayer.create(mContext, myUri(uriAudio))
    if (Build.VERSION.SDK_INT >= 21) {
        val audioAttributes: AudioAttributes =
                AudioAttributes.Builder()
                        .setUsage(AudioAttributes.USAGE_MEDIA)
                        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                        .build()
        mPlayer!!.setAudioAttributes(audioAttributes)
    } else {
        mPlayer!!.setAudioStreamType(AudioManager.STREAM_MUSIC)
    }

   
 if (mPlayer != null && !mPlayer!!.isPlaying) {
     mPlayer!!.start()
 }
Dharman
  • 30,962
  • 25
  • 85
  • 135
gpuser
  • 1,143
  • 1
  • 9
  • 6