单击列表项时播放声音文件 [英] Playing a sound file when a list item is clicked
问题描述
只是免责声明,我对android和Java都是陌生的.
Just a disclaimer, I'm very new to both android and Java.
我要追求的最终产品是类似音板的应用程序.我想显示一个声音列表,用户可以点击以播放关联的声音文件.
The end product that I'm going after in this is a soundboard like application. I want to display a list of sounds that the user can tap on to play the associated sound file.
到目前为止,我已经在我的strings.xml文件中设置了几个字符串数组.一个数组代表可用的声音,第二个数组代表实际的R.raw.soundfile资源.仅仅显示它可能会更容易.
So far I have setup a couple of string-arrays in my strings.xml file. One array represents the sounds available, and the second array represents the actual R.raw.soundfile resources. Might be easier to just show it.
<string-array name="alex_list">
<item>Sound Title</item>
</string-array>
<string-array name="alex_sounds">
<item>R.raw.soundfile</item>
</string-array>
这是我到目前为止的类定义.我真的不希望任何人像以前那样为我完成工作",但是我完全不知道从何而来.我觉得我应该从alex_list传递字符串数组位置(单击时)以从alex_sounds获得正确的资源(该资源应该立即播放,不需要媒体控件).但这就是我被困住的地方.
Here is the class definition I have so far. I really don't want anyone to "do the work for me" as it were, but I'm completely lost as to where to progress from here. I feel like I should pass the string-array position from alex_list (when clicked) to get the right resource from alex_sounds (which should play immediately, doesn't need media controls). But that's where I get stuck.
public class AlexList extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(ArrayAdapter.createFromResource(getApplicationContext(), R.array.alex_list, R.layout.list_item));
getListView().setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
// I have zero clue what to do from here
}
});
}
}
如果有更好的方法可以执行上述任何操作,请告诉我.我要做的最后一件事是在早期阶段养成不良习惯.我将继续进行处理,如果找到解决方案,请回发.
If there is a better way to do any of this, please tell me. The last thing I want to do is develop bad habits at an early stage. I'll continue to work on it and post back if I find a solution.
提前感谢您的时间!
推荐答案
以这种方式更改值数组:
Change your values array this way:
<string-array name="alex_sounds">
<item>soundfile</item>
</string-array>
然后,您的侦听器将变为:(packageName是表示R文件包的字符串:例如"com.example.main"
)
Then your listener becomes: (packageName is a string representing the package of your R file: e.g. "com.example.main"
)
@Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
String selectedFromList = getItemAtPosition(pos);
int resId = getResources().getIdentifier(selectedFromList, "raw", packageName);
MediaPlayer mp = MediaPlayer.create(AlexList.this, resId);
mp.start();
}
这将播放您在列表视图中从res/raw
文件夹中选择的名称的文件.
(在StackOverflow中快速编码,可能会出现语法错误)
This will play the file which name you selected in your list view, from your res/raw
folder.
(Coded quickly in StackOverflow, there may be syntax errors)
这篇关于单击列表项时播放声音文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!