如何播放Android通知声音

nin*_*nse 159 audio notifications android

我想知道如何在不播放媒体流的情况下播放通知声音.现在我可以通过媒体播放器这样做,但我不希望它作为媒体文件播放,我希望它作为通知或警报或铃声播放.下面是我的代码现在看起来像一个例子:

MediaPlayer mp = new MediaPlayer();
mp.reset();
mp.setDataSource(notificationsPath+ (String) apptSounds.getSelectedItem());
mp.prepare();
mp.start();
Run Code Online (Sandbox Code Playgroud)

小智 405

如果有人还在寻找解决方案,我找到了如何在Android中播放铃声/闹钟声音的答案

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

您可以将TYPE_NOTIFICATION更改为TYPE_ALARM,但是您需要跟踪您的铃声r以便停止播放...比如,当用户点击按钮或其他内容时.

  • 例如,摩托罗拉手机扩展了偏好活动,并允许用户为短信和其他类别定义通知声音.上述方法不适用于此类手机.你知道如何解决这个问题吗? (2认同)
  • 我得到了一个错误:`MediaPlayer - 应该已经设置了字幕控制器.这是什么意思? (2认同)
  • @Sam,是的./sf/ask/2791381981/.基本上,每次播放时都不要创建一个RingTone对象.创建一次,然后多次播放同一个对象. (2认同)

Rob*_*dle 205

现在,您可以通过在构建通知时包含声音而不是单独调用声音来完成此操作.

//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());
Run Code Online (Sandbox Code Playgroud)

  • 这解决了一个不同的问题 - 不是"如何播放通知声音",而是"如何播放通知*和*显示声音".接受的答案在其解决方案中是合理的. (12认同)
  • 也许您还应将其设置为通过STREAM_NOTIFICATION播放,以便使用OS当前通知音量首选项播放:.setSound(soundUri,AudioManager.STREAM_NOTIFICATION) (7认同)

aga*_*aga 47

如果要播放默认通知声音,则可以使用类的setDefaults(int)方法NotificationCompat.Builder:

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);
Run Code Online (Sandbox Code Playgroud)

我相信这是完成任务的最简单方法.


Rag*_*agu 11

试试这个:

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


cop*_*lii 9

你的问题已经有一段时间了,但是......你尝试过设置音频流类型吗?

mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
Run Code Online (Sandbox Code Playgroud)

必须在准备之前完成.