我试图制作一个简单的媒体播放器用于练习目的。代码如下所示。但是我得到了error (-38,0)
。我知道出现此错误代码是因为我在完成同步之前尚未启动mp
。但我无法解决它。
(public class MainActivity extends AppCompatActivity implements MediaPlayer.OnErrorListener, MediaPlayer.OnPreparedListener{
ArrayList<Song> songList;
MediaPlayer mp;
Uri musicUri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.list_view);
songList = new ArrayList<>();
getSongList();
Collections.sort(songList, new Comparator<Song>(){
public int compare(Song a, Song b){
return a.getTitle().compareTo(b.getTitle());
}
});
SongAdapter adapter = new SongAdapter(this, songList);
listView.setAdapter(adapter);
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
try{mp.setDataSource(MainActivity.this, musicUri);} catch (Exception e){};
try{mp.prepareAsync();} catch (Exception e){};
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
onPrepared(mp);
}
});
}
public void getSongList(){
ContentResolver musicResolver = getContentResolver();
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if (musicCursor!=null && musicCursor.moveToFirst()) {
//get columns
int titleColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
do {
Long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist));
}while (musicCursor.moveToNext());
}
if (musicCursor != null) {
musicCursor.close();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mp.release();
mp = null;
}
@Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
return false;
}
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
}