Android从变量获取R.raw [英] Android get R.raw from variable

查看:491
本文介绍了Android从变量获取R.raw的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序的原始文件夹中有声音. 有时我需要播放声音,但我不知道确切是哪一个.

i have some sounds in a raw folder on my app. And sometimes i need to play a sound, but i don't know exactly which is.

示例:

String actualSound = "hit"

playSound(mediaPlayer, R.Raw.actualSound));

我想播放R.raw.hit,但我不知道该怎么做.

I want to play the R.raw.hit but i don't know how to do that.

推荐答案

您可以使用Resources.getIdentifier()获取原始资源的数字ID,然后在播放功能中使用它:

You can obtain the numeric ID of your raw resource using Resources.getIdentifier() and then use it in your play function:

Resources res = context.getResources();
int soundId = res.getIdentifier(actualSound, "raw", context.getPackageName());
playSound(mediaPlayer, soundId);

请注意,通常不应该这样做.通过数字标识符(即R限定的常数)访问资源更为有效.如果每次要在游戏中播放声音时都执行上述操作,则尤为重要.最好使用声音名称(或更好的是:枚举值)到资源标识符甚至预加载的声音样本的映射.

Note that generally, you shouldn't do this. It is more efficient to access resources by numeric identifier (i.e. R-qualified constant). This would especially matter if you were to do the above every time you want to play sound in a game. It is better to use a mapping of sound names (or better yet: enum values) to resource identifiers or even pre-loaded sound samples.

这篇关于Android从变量获取R.raw的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆