You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取raw目录下对应指定语言的本地化MP3音频资源?

解决方案

你已经实现的字符串本地化逻辑可以直接复用,raw资源的读取逻辑和字符串一致,只需调整资源调用API即可,示例代码如下:

// 获取对应Locale的raw资源输入流
fun getLocaleRawResourceStream(requestedLocale: Locale, resId: Int, context: Context): InputStream? {
    val config = Configuration(context.resources.configuration).apply {
        setLocale(requestedLocale)
    }
    val targetLocaleContext = context.createConfigurationContext(config)
    return try {
        targetLocaleContext.resources.openRawResource(resId)
    } catch (e: Resources.NotFoundException) {
        // 无对应Locale的资源时返回null,可自行补充回退逻辑
        null
    }
}

如果需要用MediaPlayer等播放器加载音频,还可以直接获取资源的文件描述符:

// 获取对应Locale的raw资源文件描述符
fun getLocaleRawResourceFd(requestedLocale: Locale, resId: Int, context: Context): AssetFileDescriptor? {
    val config = Configuration(context.resources.configuration).apply {
        setLocale(requestedLocale)
    }
    return try {
        context.createConfigurationContext(config).resources.openRawResourceFd(resId)
    } catch (e: Resources.NotFoundException) {
        null
    }
}

注意事项

  • 请确保不同语言的同名音频存放在对应语言的raw资源目录下,比如简体中文对应res/raw-zh-rCN、英文对应res/raw-en,且相同音频的文件名在各语言目录下完全一致,才能通过同一个R.raw.xxxID匹配到对应语言的资源。
  • 如果需要将音频保存到本地,直接读取返回的InputStream写入本地文件即可。

内容的提问来源于stack exchange,提问作者Abdulsamet Kılınçarslan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:39:01