如何根据此代码播放歌曲列表中的歌曲

时间:2013-12-21 05:41:06

标签: android

这里我在列表视图中显示所有歌曲,我想基于onItemClick播放该歌曲,所以建议我如何根据我的代码进行操作 这是我的代码,用于显示来自SDcard的音频文件列表

public class ListFileActivity extends ListActivity implements OnClickListener {

private String path;
MediaPlayer mda;
int current_index2 = 0;
String filename;
Button backToRecord, allvoices;
ToggleButton activateDelete;
ListView myList;
List values;
ArrayAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.soundrecords);
     setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    backToRecord = (Button) findViewById(R.id.buttonrecord);
    activateDelete = (ToggleButton) findViewById(R.id.buttonedit);
    allvoices = (Button) findViewById(R.id.buttoncontinuous);
    myList = (ListView) findViewById(android.R.id.list);
    backToRecord.setOnClickListener(this);
    activateDelete.setOnClickListener(this);
    allvoices.setOnClickListener(this);

    // Use the current directory as title
    path = "/sdcard/";
    if (getIntent().hasExtra("path")) {
        path = getIntent().getStringExtra("path");
    }
    setTitle(path);

    // Read all files sorted into the values-array
    values = new ArrayList();
    File dir = new File(path);
    if (!dir.canRead()) {
        setTitle(getTitle() + " (inaccessible)");
    }
    final String[] list = dir.list();
    if (list != null) {
        for (String file : list) {
            if (file.contains(".3gp")) {
                values.add(file);
            }
        }
    }
    Collections.sort(values);
    // Put the data into the list
    adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_2,
            android.R.id.text1, values);
    setListAdapter(adapter);

    registerForContextMenu(myList);
}

1 个答案:

答案 0 :(得分:2)

使用onItemClick侦听器并使用MediaPlayer对象播放来自所点击项目的文件的音频uri

mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position,
            long arg3) {
        // TODO Auto-generated method stub

MediaPlayer mp = new MediaPlayer();
mp.setDataSource(path+mylist.getItemAtPosition(position).toString());
mp.prepare();
mp.play();

    }
});

}