2012-12-18 67 views
1

我有一段如下所示的代码,它获取存储在内容提供者数据库中的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

检查,如果路径是相同的,然后再次播放同样的文件,如果文件路径是不同的,那么首先复位媒体播放器,然后播放新的文件更改您的代码为:

 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(); 
} 

} 
+0

好主意,我可能会使用某种类型的变化侦听器来检查变量的值是否已经改变 – Kevik

+0

@Kevik:是只是使用另一个变量来检查文件路径是否相同,并根据路径重置“MediaPlayer”实例 –