如何播放本地文件的通知声音

时间:2017-08-02 11:50:33

标签: android notifications

    sound = Uri.parse("file://" + audioFilePath.getAbsolutePath());
    /*sound = Uri.fromFile(audioFilePath);*/
    NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(this);
            mBuilder
                    .setSmallIcon(R.drawable.notification_icon)
                    .setContentTitle(title)
                    .setContentText(description)
                    .setContentIntent(resultPendingIntent)
                    .setSound(sound);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                mBuilder.setPriority(Notification.PRIORITY_HIGH);
            }
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(1, mBuilder.build());

声音文件存在于本地存储中。通知工作正常但声音不起作用。我试过两种方式从文件路径解析Uri。

1 个答案:

答案 0 :(得分:1)

如果您将声音放在资源文件夹中(无论如何应该通知声音)并使用Notification.Builder而不是NotificationCompat.Builder,您应该可以像这样访问它:

Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + 
                       getPackageName() + "/" + R.raw.name_of_sound);
Notification.Builder mBuilder =
                new Notification.Builder(this);
        mBuilder
                .setSmallIcon(R.drawable.notification_icon)
                .setContentTitle(title)
                .setContentText(description)
                .setContentIntent(resultPendingIntent)
                .setSound(sound);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mBuilder.setPriority(Notification.PRIORITY_HIGH);
        }
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, mBuilder.build());

Source