Android Oreo(8.0/8.1)版本MediaPlayer无法正常工作问题求助
Hey there, let's dig into why your MediaPlayer's Prepared event isn't triggering on Android Oreo while working fine on other versions. I’ve run into this exact issue before, so here’s the breakdown of what’s likely going wrong and how to fix it:
1. Reattach the Prepared Listener After Resetting the MediaPlayer
On Android Oreo, calling Reset() on a MediaPlayer instance can clear existing event listeners—this behavior is stricter than in older Android versions. Right now, you only attach the Prepared listener when you first create the MediaPlayer. If you reuse the same instance (after calling Reset()), that listener might no longer be registered, which is why the event never fires.
Quick Fix:
Move the Prepared listener attachment to right after the Reset() call, so it’s re-registered every time you prepare the media:
public void Play(string pathToAudioFile) { if (_mediaPlayer != null) { _mediaPlayer.Completion -= MediaPlayer_Completion; _mediaPlayer.Stop(); } if (pathToAudioFile != null) { if (_mediaPlayer == null) { _mediaPlayer = new MediaPlayer(); } _mediaPlayer.Reset(); // Reattach the Prepared listener every time after resetting _mediaPlayer.Prepared += (sender, args) => { _mediaPlayer.Start(); _mediaPlayer.Completion += MediaPlayer_Completion; }; // Add AudioAttributes (critical for Oreo and newer) var audioAttributes = new AudioAttributes.Builder() .SetContentType(AudioContentType.Music) .SetUsage(AudioUsageKind.Media) .Build(); _mediaPlayer.SetAudioAttributes(audioAttributes); _mediaPlayer.SetDataSource(pathToAudioFile); _mediaPlayer.PrepareAsync(); } }
2. Add Required Audio Attributes
Android Oreo introduced stricter rules for audio playback. If you don’t set valid AudioAttributes, the MediaPlayer might fail to prepare silently (no error thrown, but the Prepared event won’t fire). Setting these attributes tells the system what kind of audio you’re playing, which is now a requirement for proper playback on Oreo+.
3. Add an Error Listener to Debug Further
To catch any hidden issues that might be blocking preparation, attach an Error listener to your MediaPlayer. This will log specific error codes that can help you pinpoint the root cause (like file access problems, unsupported audio formats, etc.):
// Add this right after creating/resetting the MediaPlayer _mediaPlayer.Error += (sender, args) => { Log.Error("MediaPlayerIssue", $"Error preparing audio: Code={args.What}, Extra={args.Extra}"); // Add cleanup or retry logic here if needed };
4. Double-Check File Permissions
While you mentioned other versions work, Oreo tightened up external storage access rules. If your audio file is on external storage, make sure your app has the READ_EXTERNAL_STORAGE permission, and that you’ve requested it at runtime (if you’re targeting API 23 or higher).
内容的提问来源于stack exchange,提问作者Vinodkumar

