【问题标题】:Android Notification Sound not from /resAndroid 通知声音不是来自 /res
【发布时间】:2018-11-17 23:21:19
【问题描述】:

我正在构建一个应用程序,它从 Firebase 获取音频文件,将它们保存在设备上,然后使用该音频文件作为通知声音。

我无法让音频文件作为通知声音播放。

Android 似乎只希望将声音存储在 Resources (/res) 文件夹中。相反,您似乎无法以编程方式将文件添加到 /res 文件夹。

希望能对最佳方式进行澄清。谢谢

【问题讨论】:

    标签: java android


    【解决方案1】:

    您可以使用MediaPlayer,然后使用setDataSource(String path),并将文件路径传递给它。因为媒体子系统在不同的非特权进程中运行,所以路径需要是一个世界可读的文件(例如,在外部存储上)。例如,您可以将文件转储到 Context.getExternalFilesDir() 下的某个位置。

    编辑:实际尝试回答有关通知的问题。

    Notification.Builder.setSound() 方法接受一个 URI,但它没有说明是什么类型的 URI。如果按照NotificationManagerService中的代码进入平台,它使用IRingtonPlayer播放声音(该接口不在公共SDK中)。最终使用另一个类/方法:Rintone.play()。据我所知,Ringtone 只是包装了MediaPlayer。

    长话短说,您应该能够使用全球可读的文件 URI 调用 setSound(),例如:

    Uri soundUri = Uri.parse("file://" + filePath.getAbsolutePath());
    builder.setSound(uri, ...);
    

    【讨论】:

    • 谢谢杰弗里!然后我会将什么传递给notification.setSound(...)?
    • 感谢您的更新!我将 URI 记录为“/data/user/0/com.[appPackage]/files/Sounds/[fileName]”但是在触发通知时声音不会播放,我只会收到振动。我确实验证了我可以播放默认通知声音。
    • 一个长镜头,但您可以尝试使用“file://”作为前缀。
    • 进度:现在不再播放任何内容,而是播放默认声音。
    • 我的路径是否正确,还是应该从 '/Sounds/...' 开始?
    【解决方案2】:

    这就是你需要的。

    Uri tone = Uri.parse("android.resource://" + this.getPackageName() + "/"+R.raw.notification);
    //notification refers to the file name of your mp3 file
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
           .setSmallIcon(R.mipmap.ic_launcher)
           .setContentTitle("Title")
           .setContentText("Message")
           .setSound(tone);
    

    【讨论】:

    • 谢谢,但我想播放自定义声音,而不是默认声音。
    • 欣赏编辑。我的文件不在资源文件夹中。它位于'[packageName]/files/'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    相关资源
    最近更新 更多