我已经检索了手机中存在的歌曲,但我无法播放歌曲。请帮我。我使用 setOnDataSource 但我无法得到它。在文档中它显示了 setDataSource() 的用法。请提出任何更正以使代码非常完美这是代码: package com.example.testmedia;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Tracks_media extends Activity implements OnItemClickListener {
MediaPlayer mediaplayer;
String Displayname="",id="";
Cursor cursor;
List<String> musiclist=new ArrayList<String>();
ListView tracklist;
ArrayAdapter<String> itemusic;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracks_media);
tracklist=(ListView)findViewById(R.id.TrackList);
itemusic=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, musiclist);
mediaplayer=new MediaPlayer();
tracklist.setAdapter(itemusic);
Loadmusic();
tracklist.setOnItemClickListener(this);
}
//Retrive all songs
private void Loadmusic() {
// TODO Auto-generated method stub
ContentResolver cr=getContentResolver();
Uri uri=MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
cursor=cr.query(uri, null, null, null, null);
if(cursor==null)
{
Toast.makeText(this, "No media Files present",
Toast.LENGTH_SHORT).show();
}
while (cursor.moveToNext())
{
Displayname=cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
id=cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
itemusic.add(id+"\t"+Displayname+"");
}
cursor.close();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tracks_media, menu);
return true;
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
mediaplayer.reset();
try {
mediaplayer.setDataSource(musiclist.get(position));
mediaplayer.prepare();
mediaplayer.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我尝试了很多方法,但无法做到正确。请告诉我如何播放检索的媒体。