2

我有一段代码如下所示,用于获取存储在内容提供程序数据库中的 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();

        }
4

1 回答 1

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

}
于 2012-12-18T01:30:17.353 回答