android – 显示SD卡上的所有音乐

前端之家收集整理的这篇文章主要介绍了android – 显示SD卡上的所有音乐前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用此页面代码

http://z4android.blogspot.com/2011/06/displaying-list-of-music-files-stored.html

代码正在运行,但并不太好.
当我尝试向下滚动时,ListView会不断重复列表中的歌曲.

我一直在寻找一些替代代码,但我没有找到任何代码.

谢谢你的帮助.

解决方法

我不完全确定是什么原因导致你提到的问题,但试试这个代码.
private MediaPlayer mMediaPlayer;
private String[] mMusicList;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  mMediaPlayer = new MediaPlayer();

  ListView mListView = (ListView) findViewById(R.id.listView1);

  mMusicList = getMusic();

  ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mMusicList);
  mListView.setAdapter(mAdapter);

  mListView.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> arg0,View arg1,int arg2,long arg3) {
      try {
        playSong(mMusicList[arg2]);
      } catch (IllegalArgumentException e) {
        e.printStackTrace();
      } catch (IllegalStateException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  });
}

private String[] getMusic() {
  final Cursor mCursor = managedQuery(
  MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,new String[] { MediaStore.Audio.Media.DISPLAY_NAME },null,"LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");

  int count = mCursor.getCount();

  String[] songs = new String[count];
  int i = 0;
  if (mCursor.moveToFirst()) {
    do {
      songs[i] = mCursor.getString(0);
      i++;
    } while (mCursor.moveToNext());
  }

  mCursor.close();

  return songs;
}

private void playSong(String path) throws IllegalArgumentException,IllegalStateException,IOException {
  String extStorageDirectory = Environment.getExternalStorageDirectory()
  .toString();

  path = extStorageDirectory + File.separator + path;

  mMediaPlayer.reset();
  mMediaPlayer.setDataSource(path);
  mMediaPlayer.prepare();
  mMediaPlayer.start();
}
原文链接:https://www.f2er.com/android/317583.html

猜你在找的Android相关文章