Android MediaPlayer在安装时需要文件

问题描述:

我使用android应用程序动态生成midi文件(在缓存目录中)。Android MediaPlayer在安装时需要文件

生成后,我在同一个应用程序中使用MediaPlayer播放文件。

第一次运行应用程序时,它已经需要文件在缓存目录中(应用程序崩溃)。如果我使用filemanager首先在其中放置一个虚拟文件,它将在模拟器上工作。我怎样才能绕过这个?

我需要该应用第一次在平板电脑上运行,而不需要该文件。

我使用这些命令现在:

try { 

      filePath = getCacheDir() + "/optimuse" + song + ".mid"; 
      file = new File(filePath); 

      inputStream = new FileInputStream(file); 
      if (inputStream.getFD().valid()) { 
       System.out.println("Valid!"); 
      } 
     } catch (Exception e1) { 
      e1.printStackTrace(); 
      System.exit(-1); 
     } 

     try { 
      mediaPlayer = new MediaPlayer(); 
      mediaPlayer.setDataSource(inputStream.getFD()); 
      inputStream.close(); 
     } catch (Exception e1) { 
      e1.printStackTrace(); 
      System.exit(-1); 
     } 

     try { 
      mediaPlayer.prepare(); 
     } catch (IllegalStateException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

有没有解决这个办法吗?

谢谢!

也许在使用前检查文件是否存在?您可以使用File#exists()方法实现此目的。

首先,您使用Context#getFileStreamPath(String)方法 - 其中String是您尝试访问的文件的文件名。然后你可以在返回的对象上调用File#exists()

+0

谢谢!我只是加了if(file.exists()){在第三行之后。 – dorien 2012-08-02 13:12:31