Playing a sound file when a list item is clicked

2019-07-10 08:11发布

问题:

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.

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>

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.

Thanks in advance for your time!

回答1:

Change your values array this way:

<string-array name="alex_sounds">
    <item>soundfile</item>
</string-array>

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();
}

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)