android java 正在播放 SD 卡中的 wav 音频文件

android java playing wav audio file from sd card

我无法从 SD 卡播放 wav 音频文件:

这是我的代码:

mp = new MediaPlayer(); //Defined as MediaPlayer above
        try {
            mp.setDataSource(fileNamePath);
            mp.prepare();
            mp.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

文件名路径格式如下:/storage/emulated/0/MyApp/name.wav

这是我得到的错误代码:

E/MediaPlayer: stop called in state 1, mPlayer(0x0)
E/MediaPlayer: error (-38, 0)
E/MediaPlayer: Error (-38,0)

希望你能帮帮我?

谢谢!

Android 媒体播放器对某些 wav 文件有一些问题,我建议您使用 AudioTrack 而不是 MediaPlayer。

这是一个例子:

     new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                // just put here your wav file
                File yourWavFile = new File(Environment.getExternalStorageDirectory() + "/" + AUDIO_FOLDER, fileName);
                FileInputStream fis = new FileInputStream(yourWavFile);
                int minBufferSize = AudioTrack.getMinBufferSize(16_000,
                AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
                AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 16_000,
                AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT,
                    minBufferSize, AudioTrack.MODE_STREAM);

                int i = 0;
                byte[] music = null;
                try {
                        music = new byte[512];
                        at.play();

                        while ((i = fis.read(music)) != -1)
                            at.write(music, 0, i);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    at.stop();
                    at.release();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }).start();