我有一段代码如下所示,它获取存储在内容提供商数据库中的mp3音频文件的路径名。接下来,它使用此路径名加载mp3文件并开始播放。问题是,如果我得到一个不同的路径名并点击暂停或播放它继续播放相同的旧音频文件,而不是新文件。解决这个问题的最佳方法是什么?
String pathName; // pathname of audio file stored in SD card
String selection = MediaStore.Images.Media.DATA + "='" + pathName +"'";
String[] projection = { MediaStore.Images.Media.LATITUDE };
cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, selection, null, null);
if(cursor!=null){
cursor.moveToFirst();
}
musicName = (String) cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.LATITUDE));
Toast.makeText(AudioService.this, "from AUDIOSERVICE CLASS music name: " + musicName, Toast.LENGTH_SHORT).show();
cursor.close();
player.setDataSource(musicName);
player.prepare();
player.start();
}
答案 0 :(得分:0)
检查路径是否相同然后再次播放相同的文件,如果文件路径不同,则首先重置mediaplayer,然后播放新文件,将代码更改为:
String pathName=""; // pathname of audio file stored in SD card
public static String musicName="";
String selection = MediaStore.Images.Media.DATA + "='" + pathName +"'";
String[] projection = { MediaStore.Images.Media.LATITUDE };
cursor = getContentResolver().query(MediaStore.Images.
Media.EXTERNAL_CONTENT_URI, projection, selection, null, null);
if(cursor!=null){
cursor.moveToFirst();
}
if(musicName.length()==0){
musicName = (String) cursor.getString(cursor.getColumnIndex(
MediaStore.Images.Media.LATITUDE));
Toast.makeText(AudioService.this,
"from AUDIOSERVICE CLASS music name:
" + musicName, Toast.LENGTH_SHORT).show();
cursor.close();
player.setDataSource(musicName);
player.prepare();
player.start();
}
else{
String musicNametemp = (String) cursor.getString(cursor.getColumnIndex(
MediaStore.Images.Media.LATITUDE));
if(musicNametemp.equals(musicName)){
///play old music here
}
else{
//reset mediaplayer here
if(player !=null){
player.reset();
player.release();
player = new MediaPlayer();
}
cursor.close();
musicName=musicNametemp;
player.setDataSource(musicName);
player.prepare();
player.start();
}
}