Shaishav
Shaishav

Reputation: 5312

Set AudioStreamType for an audio file played from Resource (raw folder)

[First App] I am creating a sort of Alarm app that allows user to select alarm sound from either sd-card or app-supplied sounds. Since, the app essentially plays alarms, I want the volume to be 'alarm volume' of the device. I am able to achieve this for sd card sounds. But, I am unable to setAudioStreamType for raw resource sounds.

I am using following code :

 MediaPlayer m_player = new MediaPlayer();
 m_player.setAudioStreamType(AudioManager.STREAM_ALARM);
 switch (bin_name) { //bin_name = various user selectable music files
     default:
        m_player = MediaPlayer.create(context, R.raw.blu);
        break;
 }
 m_player.setLooping(true);
 m_player.start();

My blu.mp3 plays at media volume only. Upon checking the documentation for MediaPlayer.create(Context context, int resid), I found this :

Note that since prepare() is called automatically in this method, you cannot change the audio stream type (see setAudioStreamType(int)), audio session ID (see setAudioSessionId(int)) or audio attributes (see setAudioAttributes(AudioAttributes) of the new MediaPlayer.

I also tried finding code samples for above method but none of them showed how to set AudioStreamType to AudioManager.STEAM_ALARM. I will accept answers with alternative ways that simply play the sound with infinite loop. How to achieve this ?

Upvotes: 0

Views: 1877

Answers (1)

anton
anton

Reputation: 156

As the documentation you are referring to says, you must create and prepare the MediaPlayer yourself. Haven't tried with the STREAM_ALARM but I'm using following snippet to play on STREAM_VOICE_CALL

Uri uri = Uri.parse("android.resource://com.example.app/" + R.raw.hdsweep);
MediaPlayer mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
mMediaPlayer.setDataSource(context, uri);
mMediaPlayer.prepare();
mMediaPlayer.start()

Upvotes: 3

Related Questions