1

I'm trying to implement a simple alarm in android by using the MediaPlayer. However, every time I try to prepare() it, I get an error. Here's my code. I'm a total beginner concerning Java and Android so perhaps I'm doing something inherently wrong.

private void playDiscreteAlarm()
{
    alarmSound = new MediaPlayer();
    alarmSound.setAudioStreamType(AudioManager.STREAM_RING);
    Resources res=context.getResources();
    AssetFileDescriptor fd = res.openRawResourceFd(R.raw.discrete_alarm);
    try {
        alarmSound.setDataSource(fd.getFileDescriptor());
        fd.close();
        alarmSound.setLooping(true);
        alarmSound.prepare();
        alarmSound.start();
    }
    catch (IOException e)
    {
        Log.d("error\n");
    }
}

The weird thing is that this worked once and after that stopped working. It works when I use MediaPlayer.create() however I need to use the ringer volume instead of the media volume, and I believe this is the way to do it.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
jacky la mouette
  • 523
  • 4
  • 17
  • 1
    Log the exception that you get and show us what it looks like. – Joachim Sauer Jun 05 '18 at 11:19
  • 1
    According to similar questions it's caused by a timeout within the MediaPlayer, but - as Joachim Sauer already said - we need the exception. – Seth Jun 05 '18 at 11:22
  • I'm not sure how to properly log the exception. e.toString() gave me " D/Bluebit: java.io.IOException: Prepare failed.: status=0x1" if this is what you need. sorry – jacky la mouette Jun 05 '18 at 11:48
  • @NicolasIragne Replace "Log.d("error\n");" with "Log.error(e, e)", or just "System.out.println(e)". – Seth Jun 05 '18 at 11:53
  • 1
    It gives me the same error: I/System.out: java.io.IOException: Prepare failed.: status=0x1 – jacky la mouette Jun 05 '18 at 12:03
  • 1
    Possible duplicate of [Android MediaPlayer prepare failed: status = 0x1](https://stackoverflow.com/questions/15511939/android-mediaplayer-prepare-failed-status-0x1) – Seth Jun 05 '18 at 12:30

1 Answers1

0

I fixed the problem, though I'm not sure what caused it. I just used a different and maybe slightly simpler method. Here's what I did:

private void playDiscreteAlarm()
{
    String filename = "android.resource://" + context.getPackageName() + "/raw/discrete_alarm";

    alarmSound = new MediaPlayer();
    alarmSound.setAudioStreamType(AudioManager.STREAM_RING);
    try {
        alarmSound.setDataSource(context, Uri.parse(filename));
        alarmSound.setLooping(true);
        alarmSound.prepare();
        alarmSound.start();
    }
    catch (Exception e)
    {
        System.out.println(e);
    }
}

Thanks !

jacky la mouette
  • 523
  • 4
  • 17