无法在Android中的MediaPlayer上播放音频

时间:2015-11-24 19:56:21

标签: android audio

这里是Android编码新手。我试图让用户为MediaPlayer选择一个音频文件,使用"上传"按钮,然后一旦用户点击播放,MediaPlayer就应该开始播放文件。"到目前为止,这是我的代码:

 public class MainActivity extends Activity {
        final int ACTIVITY_CHOOSE_FILE = 1;
        File original;


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

            Button button = (Button) this.findViewById(R.id.button);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent chooseFile;
                    Intent intent;
                    chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
                    chooseFile.setType("audio/mpeg");
                    intent = Intent.createChooser(chooseFile, "Choose a file");
                    startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
                }
            });

            Button playButton = (Button)findViewById(R.id.playbutton);
            playButton.setOnClickListener(new Button.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MediaPlayer mediaPlayer = new MediaPlayer();
                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    try {
                        mediaPlayer.setDataSource(original.getAbsolutePath());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            mp.start();
                        }
                    });

                }
            });
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            switch (requestCode) {
                case ACTIVITY_CHOOSE_FILE: {
                    if (resultCode == RESULT_OK) {
                        Uri uri = data.getData();
                        original = new File(uri.getPath());
                        String tag = "TAG";
                        Log.d(tag, original.getAbsolutePath());
                    }
                }
            }
        }
    }

我可以选择音频文件,但是一旦我点击播放就没有任何反应。我做错了什么?

1 个答案:

答案 0 :(得分:0)

设置mediaPlayer数据源后,您必须致电mediaPlayer.prepareAsync()

Media Playback in android