MediaPlayer.setDataSource()没有捕获异常

时间:2016-06-30 07:49:10

标签: android uri android-mediaplayer

如果媒体播放器读取的音频文件不存在,我想捕获异常。从URI中,我得到了以下代码:

try{player.setDataSource(getApplicationContext(), uri); }

    catch (IllegalStateException e) {Log.e("MUSIC", "Error setting data source", e);}
    catch (IOException e) {Log.e("MUSIC", "Error setting data source", e);}
    catch(IllegalArgumentException e){ Log.e("MUSIC", "Error setting data source", e); }
    catch(SecurityException e){ Log.e("MUSIC", "Error setting data source", e); }

player.prepareAsync(); 

但是,即使URI错误,似乎永远不会引发异常。 我可能在这里遗漏了一些明显的东西,但是如果uri不存在,捕获异常以便不启动读数的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

由于J的评论,我终于找到了一个解决方案来测试文件是否存在。由于文件位于我的原始文件夹中,因此有点棘手。我使用this来解决它。

最后,我的代码如下:

file_name ="name_of_the_ressource_whitout_directory_or_extension";
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/raw/" + file_name);

int checkExistence = getResources().getIdentifier(file_name, "raw", getPackageName());

if (checkExistence != 0){

        // The audio file exists

        try{
            player.setDataSource(getApplicationContext(), uri);
            player.prepareAsync();
        }

        catch (IllegalStateException e) {Log.e("MUSIC SERVICE", "Error setting data source", e);}
        catch (IOException e) {Log.e("MUSIC SERVICE", "Error setting data source", e); }
        catch(IllegalArgumentException e){ Log.e("MUSIC SERVICE", "Error setting data source", e);  }
        catch(SecurityException e){ Log.e("MUSIC SERVICE", "Error setting data source", e); }

请注意,我现在不确定try / catch的效用。