Search code examples
javaandroidandroid-mediaplayer

Error code (1, -2147483648) in Android MediaPlayer


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.


Solution

  • 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 !