web-dev-qa-db-fra.com

Comment jouer un son de notification Android

Je me demandais comment je pouvais lire un son de notification sans le lire via le flux multimédia. À l'heure actuelle, je peux le faire via le lecteur multimédia. Cependant, je ne souhaite pas qu'il soit lu comme un fichier multimédia, je veux qu'il soit lu comme une notification, une alerte ou une sonnerie. Voici un exemple de mon code actuel:

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

Si quelqu'un cherche toujours une solution à ce problème, j'ai trouvé une réponse à Comment jouer à la sonnerie/sonnerie dans Android

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

Vous pouvez remplacer TYPE_NOTIFICATION par TYPE_ALARM, mais vous voudrez garder une trace de votre sonnerie r pour l’arrêter de la lire… disons, lorsque l’utilisateur clique sur un bouton ou quelque chose.

376
Phidius

Vous pouvez maintenant le faire en incluant le son lors de la création d'une notification plutôt que d'appeler le son séparément.

//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());
199
Rob Riddle

Si vous souhaitez qu'un son de notification par défaut soit joué, vous pouvez utiliser 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);

Je crois que c'est le moyen le plus simple d'accomplir votre tâche.

46
aga

Cela fait un bon bout de temps que votre question, mais ... Avez-vous essayé de définir le type de flux audio?

mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

Cela doit être fait avant de préparer.

9
copolii

Essaye ça: 

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

J'avais à peu près la même question. Après quelques recherches, je pense que si vous voulez jouer au "son de notification" du système par défaut, vous devez afficher une notification et lui dire d'utiliser le son par défaut. Et il y a quelque chose à dire pour l'argument dans certaines des autres réponses selon lequel si vous jouez un son de notification, vous devriez également présenter un message de notification.

Cependant, modifiez légèrement l'API de notification et vous pourrez vous rapprocher de ce que vous souhaitez. Vous pouvez afficher une notification vierge, puis la supprimer automatiquement après quelques secondes. Je pense que cela fonctionnera pour moi; peut-être que cela fonctionnera pour vous.

J'ai créé un ensemble de méthodes pratiques dans com.globalmentor.Android.app.Notifications.Java qui vous permettent de créer un son de notification ressemblant à ceci:

Notifications.notify(this);

La LED clignotera également et, si vous avez l'autorisation de vibrer, une vibration se produira. Oui, une icône de notification apparaîtra dans la barre de notification mais disparaîtra après quelques secondes.

À ce stade, vous réaliserez peut-être que, puisque la notification disparaîtra de toute façon, vous pourriez aussi bien avoir un message défilant dans la barre de notification; vous pouvez faire ça comme ça:

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

Il existe de nombreuses autres méthodes pratiques dans cette classe. Vous pouvez télécharger la bibliothèque entière à partir de son référentiel Subversion et la construire avec Maven. Cela dépend de la bibliothèque globalmentor-core, qui peut également être construite et installée avec Maven.

2
Garret Wilson
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());
    }
}
1
dsc clg

Vous pouvez utiliser Notification et NotificationManager pour afficher la notification souhaitée. Vous pouvez ensuite personnaliser le son que vous voulez jouer avec votre notification.

1
Valentin Rocher

Définir le son sur le canal de notification

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

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

        channel.setSound(alarmUri, attributes);
0
Milind Chaudhary

Je pense que le concept de "notification sonore" est quelque peu faux pour l'interface utilisateur Android.

Le comportement attendu d'Android consiste à utiliser la notification standard pour alerter l'utilisateur. Si vous jouez un son de notification sans l'icône de la barre d'état, vous confondez l'utilisateur ("qu'est-ce que c'était que ce son? Il n'y a pas d'icône ici, j'ai peut-être des problèmes d'audition?").

Comment régler le son sur une notification, par exemple, ici: Réglage du son pour la notification

0
think01