[android] How to play an android notification sound

I was wondering how I could play a notification sound without playing it over the media stream. Right now I can do this via the media player, however I don't want it to play as a media file, I want it to play as a notification or alert or ringtone. heres an example of what my code looks like right now:

MediaPlayer mp = new MediaPlayer();
mp.reset();
mp.setDataSource(notificationsPath+ (String) apptSounds.getSelectedItem());
mp.prepare();
mp.start();

This question is related to android audio notifications

The answer is


You can use Notification and NotificationManager to display the notification you want. You can then customize the sound you want to play with your notification.


It's been a while since your question, but ... Have you tried setting the Audio stream type?

mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

It must be done before prepare.


I had pretty much the same question. After some research, I think that if you want to play the default system "notification sound", you pretty much have to display a notification and tell it to use the default sound. And there's something to be said for the argument in some of the other answers that if you're playing a notification sound, you should be presenting some notification message as well.

However, a little tweaking of the notification API and you can get close to what you want. You can display a blank notification and then remove it automatically after a few seconds. I think this will work for me; maybe it will work for you.

I've created a set of convenience methods in com.globalmentor.android.app.Notifications.java which allow you create a notification sound like this:

Notifications.notify(this);

The LED will also flash and, if you have vibrate permission, a vibration will occur. Yes, a notification icon will appear in the notification bar but will disappear after a few seconds.

At this point you may realize that, since the notification will go away anyway, you might as well have a scrolling ticker message in the notification bar; you can do that like this:

Notifications.notify(this, 5000, "This text will go away after five seconds.");

There are many other convenience methods in this class. You can download the whole library from its Subversion repository and build it with Maven. It depends on the globalmentor-core library, which can also be built and installed with Maven.


You can now do this by including the sound when building a notification rather than calling the sound separately.

//Define Notification Manager
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

//Define sound URI
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
        .setSmallIcon(icon)
        .setContentTitle(title)
        .setContentText(message)
        .setSound(soundUri); //This sets the sound to play

//Display notification
notificationManager.notify(0, mBuilder.build());

If you want a default notification sound to be played, then you can use setDefaults(int) method of NotificationCompat.Builder class:

NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(someText)
                .setDefaults(Notification.DEFAULT_SOUND)
                .setAutoCancel(true);

I believe that's the easiest way to accomplish your task.


I think the concept of "notification sound" is someway wrong for Android UI.

The Android expected behaviour is to use the standard Notification to alert the user. If you play a notification sound without the status bar icon, you get the user confused ("what was that sound? there is no icon here, maybe I have hearing problems?").

How to set sound on a notification is, for example, here: Setting sound for notification


Intent intent = new Intent(this, MembersLocation.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("type",type);
    intent.putExtra("sender",sender);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    String channelId = getString(R.string.default_notification_channel_id);

    Uri Emergency_sound_uri=Uri.parse("android.resource://"+getPackageName()+"/raw/emergency_sound");
   // Uri Default_Sound_uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    if(type.equals("emergency"))
    {
        playSound=Emergency_sound_uri;
    }
    else
    {
        playSound= Settings.System.DEFAULT_NOTIFICATION_URI;
    }

    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.drawable.ic_notification)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setSound(playSound, AudioManager.STREAM_NOTIFICATION)
                    .setAutoCancel(true)
                    .setColor(getColor(R.color.dark_red))
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setContentIntent(pendingIntent);

   // notificationBuilder.setOngoing(true);//for Android notification swipe delete disabling...

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_HIGH);
        AudioAttributes att = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                .build();
        channel.setSound(Emergency_sound_uri, att);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
    }

    if (notificationManager != null) {
        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}

Set sound to notification channel

        Uri alarmUri = Uri.fromFile(new File(<path>));

        AudioAttributes attributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_ALARM)
                .build();

        channel.setSound(alarmUri, attributes);

Try this:

public void ringtone(){
    try {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
        r.play();
     } catch (Exception e) {
         e.printStackTrace();
     }
}

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to audio

How to prevent "The play() request was interrupted by a call to pause()" error? Creating and playing a sound in swift How to play or open *.mp3 or *.wav sound file in c++ program? How to playback MKV video in web browser? Play audio as microphone input HTML embed autoplay="false", but still plays automatically Autoplay an audio with HTML5 embed tag while the player is invisible Playing mp3 song on python Javascript Audio Play on click Play sound on button click android

Examples related to notifications

NotificationCompat.Builder deprecated in Android O No notification sound when sending notification from firebase in android Android Push Notifications: Icon not displaying in notification, white square shown instead How to display multiple notifications in android Actionbar notification count icon (badge) like Google has How to display count of notifications in app launcher icon Android notification is not showing How to create a notification with NotificationCompat.Builder? Open application after clicking on Notification How to fix "no valid 'aps-environment' entitlement string found for application" in Xcode 4.3?