开发者

Playing a raw audio clip by variable name

开发者 https://www.devze.com 2023-04-05 13:20 出处:网络
I have a quick question that\'s been bugging me for a while.Is it possible to access files in the raw directory by using a variable name?Let me explain.

I have a quick question that's been bugging me for a while. Is it possible to access files in the raw directory by using a variable name? Let me explain.

I have over 100 sound clips in my raw/ directory named sound1, sound2, sound3 and so on. In my app, I have a list view that pulls each line from a string array开发者_Go百科. What I want to do is, when you tap on a certain line, the app players the sound of the corresponding audio file.

For example, if I tapped on the 16th item in my list, it plays sound17 (compensating for lists starting at 0). As far as I can tell, I can only access files in raw with "R.raw.filename" which I guess is some sort of memory pointer? Because if i try to do something like this:

public void onItemClick(AdapterView<?> parent, View arg1, int position,long arg3) {
  long clipid = parent.getItemIdAtPosition(position);
  MediaPlayer clip = MediaPlayer.create(SoundList.this, "R.raw.sound" + clipid);
  clip.start();
}

Obviously it won't know what "R.raw.sound" + clipid is. Is there any possible way to do this?

EDIT Just figured it out after a bit more searching. Here is what I used:

public void onItemClick(AdapterView<?> parent, View arg1, int position,long arg3) {
  long clipid = parent.getItemIdAtPosition(position);
  int resId = getResources().getIdentifier("sound"+clipid, "raw", "com.example.mypackage");
  MediaPlayer clip = MediaPlayer.create(SoundList.this, resId);
  clip.start();
}


Try this:

MediaPlayer clip = MediaPlayer.create(SoundList.this, getResources().getIdentifier(clipid, "raw","{android package id}"));

You'll need to specify the package used in your AndroidManifest.xml file, but that should do what you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消