MediaPlayer不播放手机中的音频文件

问题描述 投票:0回答:1

我想播放位于手机中的mp3文件,但我得到例外。我尝试了很多解决方案,但都没有。有人能告诉我的代码有什么问题吗?

pathToFile = /storage/emulated/0/Download/cw200_pod.mp3

mediaPlayer = new MediaPlayer();

try {
    mediaPlayer.setDataSource(pathToFile);
    mediaPlayer.prepareAsync();
    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            mediaPlayer.start();
        }
    });
} catch (IOException e) {
    throw new IllegalStateException(e.getMessage());
}

我的明显权限

<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />

例外

08-29 23:37:55.313 15523-15523/apps.robot.myownsoundboard E/AndroidRuntime: FATAL EXCEPTION: main
Process: apps.robot.myownsoundboard, PID: 15523
java.lang.IllegalStateException: setDataSource failed.
    at apps.robot.myownsoundboard.activity.RecordActivity.lambda$onCreate$2$RecordActivity(RecordActivity.java:109)
    at apps.robot.myownsoundboard.activity.RecordActivity$$Lambda$2.onClick(Unknown Source)
    at android.view.View.performClick(View.java:5207)
    at android.view.View$PerformClick.run(View.java:21177)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5437)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
java android
1个回答
-1
投票

将您的声音放在res / raw文件夹中。

final MediaPlayer mp = MediaPlayer.create(this, R.raw.sound);

Button play_button = (Button)this.findViewById(R.id.button);
play_button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Log.v(TAG, "Playing sound...");
        mp.start();
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.