Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly set MediaPlayer audio stream type

Tags:

android

audio

I'm trying to create a way to adjust volume settings for each of the different streams (media, notification, ringtone, etc) and have a way to preview the output sound level of each stream. I believe I have the correct implementation, but when I set the output stream type, there is no sound that plays.

Here is the code that correctly plays the user's selected alarm sound:

Uri mediaUri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
MediaPlayer mp=MediaPlayer.create(getApplicationContext(), mediaUri);
//mp.setAudioStreamType(AudioManager.STREAM_ALARM);
mp.start();`

That commented out line is what is causing me problems. I would like to hear the alarm sound at the volume levels of the different audio streams, but when I include that line for STREAM_ALARM or any other audio stream, no sound at all plays. Any ideas what could be going on here?

like image 203
Ryan Zink Avatar asked Aug 21 '10 04:08

Ryan Zink


People also ask

What is audio stream in Android?

Streaming an audio media consists to receive constantly data from a remote source and to deliver the audio data received to the end-user. Nowadays, everyone uses streaming platforms daily.

What class in Android can play audio?

One of the most important components of the media framework is the MediaPlayer class. An object of this class can fetch, decode, and play both audio and video with minimal setup.

How do I play audio files on Android?

Prepare media file: To play a media file, you need to first prepare it i.e. you need to load the file for playback. Methods used for doing this are prepare(), prepareAsync(), and setDataSource(). Start/Pause the playback: After loading the media file, you can start playing the media file by using the start() method.


1 Answers

Okay, I found the solution after a bit more testing and it looks like this, in case anyone else runs into the same problem I was having. The MODIFY_AUDIO_SETTINGS permission is needed in the Manifest for this to work.

AudioManager am=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_NORMAL);
MediaPlayer mp=new MediaPlayer();
Uri ringtoneUri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
try
{
    mp.setDataSource(getApplicationContext(), ringtoneUri);
    mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
    mp.prepare();
    mp.start();
}
catch(Exception e)
{
    //exception caught in the end zone
}
like image 63
Ryan Zink Avatar answered Oct 02 '22 16:10

Ryan Zink