使用Android VideoView播放视频时出现“无法播放此视频”错误求助
Hey there! Let's figure out why your VideoView is throwing that "Can't play this video" error. I've looked over your code and here are the most likely fixes to try:
- Android's
VideoViewhas strict format rules—it mainly supports MP4 files encoded with H.264 video and AAC audio. If yourksnnfile is in another format (like MKV, FLV, or uses an unsupported codec), that's almost certainly the root cause. - Also, confirm your filename in the
res/rawfolder is all lowercase, with no spaces or special characters (underscores are fine). Android resource names are case-sensitive, soKSNN.mp4won't matchR.raw.ksnn.
Right now you're starting the video before attaching the MediaController, which can mess up playback. Rearrange your code to set up the controller before calling start():
btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.ksnn); // Initialize and attach MediaController first mediaController = new MediaController(VideoTutorial.this); videoView.setMediaController(mediaController); // Make sure the controller anchors to your VideoView mediaController.setAnchorView(videoView); videoView.setVideoURI(uri); videoView.start(); } });
I added mediaController.setAnchorView(videoView) here—this ensures the controller is properly linked to your VideoView, which is a common oversight.
Sometimes the video isn't fully loaded when you call start(), leading to playback failures. Add an OnPreparedListener to wait until the video is ready to play:
// Add this in your onCreate method, after initializing videoView videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.start(); // Optional: Adjust scaling to fit your VideoView videoView.setVideoScalingMode(VideoView.VIDEO_SCALING_MODE_SCALE_TO_FIT); } });
Then update your onClick handler to remove the direct videoView.start()—let the listener handle it once the video is ready:
btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.ksnn); mediaController = new MediaController(VideoTutorial.this); videoView.setMediaController(mediaController); mediaController.setAnchorView(videoView); videoView.setVideoURI(uri); // Remove videoView.start() here } });
Double-check that ksnn is directly in the res/raw directory (no nested subfolders). If you just added the file, clean and rebuild your project—Android Studio sometimes doesn't pick up new resources automatically.
If none of the above fixes work, try replacing ksnn with a sample MP4 file that you know plays on Android. This will help you confirm if the issue is with your code or the video file itself.
内容的提问来源于stack exchange,提问作者Sabir Hala

