使用mediaplayer的FileNotFoundException

时间:2018-03-15 15:35:16

标签: java android file exception android-mediaplayer

我正试图解决这个问题几个小时,但找不到合适的解决方案: 我正在尝试播放媒体文件(Mp3 / Ogg),但总是得到FileNotFoundException(我确定它在那里;)

这是我尝试的:

检查SD卡是否可用。

检查是否授予读/写权限。

加载/播放歌曲。

if(isExternalStorageReadable() && isExternalStorageWritable())
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            Log.v("Permission","Readingpermission is granted");
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            Log.v("Permission","Writingpermission is granted");
        }
        playSong(getExternalFilesDir(Environment.DIRECTORY_MUSIC).toString() + "/t1.mp3");

到目前为止,这部分代码正在运作。

但是一旦谈到playSong(String):

try {
        MediaPlayer mediaplayer = new MediaPlayer();
        mediaplayer.setDataSource(path);
        mediaplayer.prepare();
        mediaplayer.start();
    } catch (Exception e){
        Log.e("Mediaplayer", e.toString());
    }

程序崩溃尝试使用此例外的setDataSource:

E/Mediaplayer: java.io.FileNotFoundException: /storage/emulated/0/Android/data/OMSclient.omsgui/files/Music/t1.mp3

我错过了什么?我很傻。

提前致谢。

修改

好吧,我发现了以下问题:

如果我只是执行

playSong("storage/17E5-1C14/Android/data/OMSclient.omsgui/files/Music/t1.ogg");

它工作正常,但如果我使用:

playSong("/storage/emulated/0/Android/data/OMSclient.omsgui/files/Music/t1.mp3");

playSong( “存储/模拟/ 0 / Android设备/数据/ OMSclient.omsgui /文件/音乐/ t1.mp3”);

它没有..

为什么呢? ...

3 个答案:

答案 0 :(得分:0)

使用此代码,

 events = [
        {
          'id': 1,
          'title': u'HHGHHMjshjskksjks',
          'description': u'Cras justo odio dapibus ac facilisis in egestas eget qua ', 
          'location':'jkknxjnj',
          'category':'party',
          'rsvp': False,
          'event_owner':1
        },

        {
          'id': 2,
          'title': u'khjhjshjsjhdndjdh',
          'description': u'jhhnbsbnsbj', 
          'location':'jhjhsjhjhsjhjdhsd',
          'category':'party',
          'rsvp': False,
          'event_owner':2
        },

        {
          'id': 3,
          'title': u'jhjshjsdhjshdjshjsd',
          'description': u'Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec  elit non mi porta gravida at eget metus.', 
          'location':'kjkshjhjhjbsnbsd',
          'category':'party',
          'rsvp': False,
          'event_owner':2
        },

        {
          'id': 4,
          'title': u'jjhjshjhsjhjshjjhjhd',
          'description': u'Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec  elit non mi porta gravida at eget metus.', 
          'location':'kjisisiisdsds',
          'category':'party',
          'rsvp': False,
          'event_owner':2
          },

          {
            'id': 5,
            'title': u'uiujsdshuuihuyksjhjs',
            'description': u'Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec  elit non mi porta gravida at eget metus.', 
            'location':'sjnsisuis',
            'category':'party',
            'rsvp': False,
            'event_owner':2
          },

          {
          'id': 6,
          'title': u'iusijksuiksuhj suyuys jhu ',
          'description': u'Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec  elit non mi porta gravida at eget metus.', 
          'location':'isuisiiws',
          'category':'party',
          'rsvp': False,
          'event_owner':2
          },

          {
          'id': 7,
          'title': u'jujusi jsuoios jshuysd',
          'description': u'Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec  elit non mi porta gravida at eget metus.', 
          'location':'area h',
          'category':'party',
          'rsvp': False,
          'event_owner':2
          },
    ]

希望它有帮助!

答案 1 :(得分:0)

我使用您提供的代码和以下属性创建了一个项目:

compileSdkVersion 26
minSdkVersion 19
targetSdkVersion 19

我发现getExternalFilesDir(Environment.DIRECTORY_MUSIC).toString()会返回不同的值,具体取决于模拟器的Android级别。

等级19 KitKat 4.4 /storage/sdcard/Android/data/com.test.mediaplayerproblem/files/Music/test1.mp3

25级牛轧糖7.1.1 /storage/emulated/0/Android/data/com.test.mediaplayerproblem/files/Music/test1.mp3

这里有我的代码,但请记住,我从原始资源中保存文件并在同一个活动中播放,因此它总是在正确的位置。

MainActivity.java:

public class MainActivity extends AppCompatActivity
{
    private MediaPlayer mediaplayer;
    private String musicDirPath;
    private String filename = "/test1.mp3";

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        musicDirPath = getExternalFilesDir(Environment.DIRECTORY_MUSIC).toString();
        TextView tv1 = findViewById(R.id.textView1);
        tv1.setText(musicDirPath + filename);
        Log.v("Mediaplayer", musicDirPath + filename);
    }

    public void playFile(View view) {
        if(isExternalStorageReadable() && isExternalStorageWritable())
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                Log.v("Permission","Readingpermission is granted");
            }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            Log.v("Permission","Writingpermission is granted");
        }
        playSong(getExternalFilesDir(Environment.DIRECTORY_MUSIC).toString() + "/test1.mp3");
    }

    public void playSong(String path) {
        try {
            mediaplayer = new MediaPlayer();
            mediaplayer.setDataSource(path);
            mediaplayer.prepare();
            mediaplayer.start();
        } catch (Exception e){
            Log.e("Mediaplayer", e.toString());
        }
    }

    public void stopFile(View view) {
        if (mediaplayer != null) {
            try {
                mediaplayer.stop();
                mediaplayer.release();
                mediaplayer = null;
            } catch(Exception e) {
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        }
    }

    public void saveFile(View view) {

        byte[] buffer = null;
        InputStream fis = getResources().openRawResource(R.raw.finn1);
        int size = 0;

        try
        {
            size = fis.available();
            buffer = new byte[size];
            fis.read(buffer);
            fis.close();

            boolean exists = (new File(musicDirPath + filename)).exists();
            if (exists)
            {
                Toast.makeText(this, "File exists!", Toast.LENGTH_SHORT).show();
            }
            else
            {
                FileOutputStream save = new FileOutputStream(musicDirPath + filename);
                save.write(buffer);
                save.flush();
                save.close();
                Toast.makeText(this, "File saved!", Toast.LENGTH_SHORT).show();
            }
        }
        catch (IOException e)
        {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    /* Checks if external storage is available for read and write */
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    /* Checks if external storage is available to at least read */
    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            return true;
        }
        return false;
    }
}

activity_main.xml中:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.test.mediaplayerproblem.MainActivity">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView1"
            android:text="Hello World!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/saveFile"
                android:text="Save"
                android:onClick="saveFile"/>
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/playButton"
                android:text="Play"
                android:onClick="playFile"/>
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/stopButton"
                android:text="Stop"
                android:onClick="stopFile"/>
        </LinearLayout>
    </LinearLayout>

</android.support.constraint.ConstraintLayout>

答案 2 :(得分:0)

好的。因为getExternalFilesDir似乎不起作用,我使用了以下解决方法:

public String getExternalPath(){
    String removableStoragePath = "";
    File fileList[] = new File("/storage/").listFiles();
    for (File file : fileList)
    { if(!file.getAbsolutePath().equalsIgnoreCase(Environment.getExternalStorageDirectory().getAbsolutePath()) && file.isDirectory() && file.canRead())
        removableStoragePath = file.getAbsolutePath(); }
    return removableStoragePath;
}

这个代码在我测试它的每个模拟器上运行良好。 希望这有帮助,如果有人遇到同样的问题。