我收聽了我手機中的歌曲, 但我無法播放歌曲。請幫幫我。我使用setOnDataSource,但我無法得到它。在文檔中,它顯示使用setDataSource()。請提出任何更正以使代碼非常完美 以下是代碼: package com.example.testmedia;如何在Android中播放媒體文件
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();
}
}
}
我嘗試了很多方法,但無法做到正確。 請告訴我如何播放retrived媒體。
有沒有其他的方式去做 –