将字符串转换为MP3播放资源的Uri

人气:1,116 发布:2022-09-11 标签: java android

问题描述

我尝试播放使用媒体播放器类的MP3。当我辛苦code它工作的MP3资源,但是我想资源来自一个字符串,而不是直接访问它像 R.raw.mp3name

I am trying to play an mp3 using the Media player class. When I hardcode the mp3 resource it works, however I would like the resource to come from a string instead of directly accessing it like R.raw.mp3name.

Bundle bundle = getIntent().getExtras();
String Choice= bundle.getString("bundledChoice");        
Uri myUri = Uri.parse("R.raw." + Choice);        
mPlayer = MediaPlayer.create(activity.this, myUri);
mPlayer.start();

如果我更改了倒数第二行以 = MPLAYER MediaPlayer.create(activity.this,R.raw.song)它会工作,问题是创建从由束中获得的字符串动态资源URI

If I change the second to last line to mPlayer = MediaPlayer.create(activity.this, R.raw.song) it will work, the problem is creating the resource URI dynamically from the string which is obtained from the bundle.

请指教。

推荐答案

我使用这个小的挑战是基于@造物主的回答这个主题的解决方案:Android - 获取图像资源到乌里:抛出:IllegalArgumentException

The solution I am using to this little challenge is based on @Creator's answer to this post: Android - getting an image resource into Uri: IllegalArgumentException.

的解决方案是使用

Uri uri = Uri.parse("android.resource://[package]/[res type]/[res name]");

【包装】您可能知道(com.company.blah.superdooperthing),也可以使用getPackageName()来确定。

[package] you either know (com.company.blah.superdooperthing), or can be determined using getPackageName().

[RES类型](我认​​为,它似乎工作)里面的目录RES你是从拉动资源。因此,对于音频文件... / RES /生/ nicemusic.mp3,资源将是原始。

[res type] is (I think, and it seems to work) the directory inside "res" that you are pulling the resource from. So, for an audio file .../res/raw/nicemusic.mp3, res would be "raw".

[RES名称]是(我认为,它似乎工作)的种源的文件名(不扩展)。因此,对于上面的例子,这将是nicemusic

[res name] is (I think, and it seems to work) the file name (less extension) of the resouce. So, for the example above, it would be "nicemusic".

因此​​,一个更系统的方法可能是:

So, a more systematic approach might be:

String dataResourceDirectory = "raw";
String dataResoruceFilename = "nicemusic";

Uri uri=Uri.parse("android.resource://" + getPackageName() + "/" + 
                  dataResourceDirectory + "/" + dataResoruceFilename);

更好的解决方案表示欢迎!

Better solutions welcome!

105