简体   繁体   中英

MediaPlayer loading sound from Uri not working

I have a simple voice recorder app. When the user records something it gets saved on the external storage and after that it gets played from there.

Everything works fine except on a Huawei P8 Lite smartphone with Android 6.

Here is how I play the sound:

    Thread th=new Thread(new Runnable() {
        @Override
        public void run() { 
            try {
                MediaPlayer mp = new MediaPlayer();
                mp.setDataSource(view.getContext(), uri);
                mp.prepare();
                mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        mp.release();
                    }
                });

                mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mp.start();
                    }
                });

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //send message to handler
        }
    });
    th.start();

The Uri does exist at this moment and also the file does exist in the destination. Why is my mediaPlayer not playing anything? The permissions are given at this point where it tries to create the MediaPlayer so it should not be a permission issue.

All I get in the logcat is:

W/MediaPlayer-JNI: MediaPlayer finalized without being released 
I/MediaPlayer: setDataSource(34, 0, 576460752303423487) 
I/MediaPlayer: [HSM] stayAwake true uid: 10255, pid: 22592 
E/MediaPlayer: error (-19, 0) 
E/MediaPlayer: Error (-19,0)

Like I said it works fine on all other devices I tested (Android 10 & Android 9)

EDIT

Here is what I tried: I created Emulators with every API level from API 18 to 30 and it works fine on every emulator. I reseted my Huawei P8 Lite smartphone to factory settings. I checked if the sound file is saved properly and if I can open and play it manualy when I navigate in the folder where it gets saved (it works perfectly so it has nothing to do with the code that saves the sound) I really run out of ideas.

Hope someone can help, Thanks!

You need to player prepare asynchronously. player. prepare() player. prepare() replace with below code:

player.prepareAsync()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM