MediaPlayer准备失败:status = 0x1

时间:2014-01-30 05:59:07

标签: android file

我一直在努力从sdcard获取音乐文件列表,但我很成功,但问题是,当我点击一个文件时,它应该播放该文件,但它给了我这个错误。 这是我的代码:

    private String[] mMusicList;
static long playlistid=0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  mMediaPlayer = new MediaPlayer();

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

  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, 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;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

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

  path = extStorageDirectory + File.separator + path;

  mMediaPlayer.reset();
  FileInputStream fis = new FileInputStream(path);
  mMediaPlayer.setDataSource(fis.getFD());
  mMediaPlayer.prepare();
  mMediaPlayer.start();
}

1 个答案:

答案 0 :(得分:0)

好的,首先删除mCursor.close()。在这里你关闭光标,这在大多数时候是个问题。

其次,明显的错误是您在mediaplayer中指定的路径。您正在提供separator的路径。

path = extStorageDirectory + File.separator + path;
FileInputStream fis = new FileInputStream(path);
mMediaPlayer.setDataSource(fis.getFD());

哪个错误,找不到文件。

而是将代码更改为

mMediaPlayer.setDataSource(extStorageDirectory);

希望你明白了。 欢呼:)