fix: 修复视频播放稳定性和返回桌面更换逻辑
- 修复视频播放错误时的无限循环问题,不再在 onError 中重新调用 drawWallpaper - 延迟 Surface 绑定到 onPrepared 回调,提高 MediaPlayer 兼容性 - 添加 hasError 状态追踪,防止在错误状态下执行 pause/resume - 使用独立的 changeOnReturn 标志修复返回桌面更换壁纸逻辑 - 集中管理媒体扩展名常量到 MediaType 枚举 - 添加 fromUri() 方法支持根据文件扩展名判断媒体类型 - 优化 UI 显示,分别统计图片和视频数量 - 添加 hasMedia() 和 getMediaSummary() 方法简化代码 Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude <noreply@anthropic.com> Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
1 parent
abea466a2f
commit
8be16620a7
8 files changed
+253
-81
No files matched your search
@@ -143,8 +143,45 @@ public class Album implements Serializable {
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取相册中的图片总数
|
||||
* 获取相册中的媒体总数(不包括文件夹内的文件)
|
||||
*/
|
||||
public int getMediaCount() {
|
||||
int images = imageUris != null ? imageUris.size() : 0;
|
||||
int videos = videoUris != null ? videoUris.size() : 0;
|
||||
return images + videos;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取媒体统计摘要(用于 UI 显示)
|
||||
*/
|
||||
public String getMediaSummary() {
|
||||
int folderCount = folders != null ? folders.size() : 0;
|
||||
int imageCount = imageUris != null ? imageUris.size() : 0;
|
||||
int videoCount = videoUris != null ? videoUris.size() : 0;
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (folderCount > 0) {
|
||||
sb.append(folderCount).append(" 个文件夹");
|
||||
}
|
||||
if (imageCount > 0) {
|
||||
if (sb.length() > 0) sb.append(" · ");
|
||||
sb.append(imageCount).append(" 张图片");
|
||||
}
|
||||
if (videoCount > 0) {
|
||||
if (sb.length() > 0) sb.append(" · ");
|
||||
sb.append(videoCount).append(" 个视频");
|
||||
}
|
||||
|
||||
if (sb.length() == 0) {
|
||||
return "无媒体内容";
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use getMediaCount() or folders.size()
|
||||
*/
|
||||
@Deprecated
|
||||
public int getImageCount() {
|
||||
return folders.size();
|
||||
}
|
||||
|
||||
@@ -64,4 +64,14 @@ public class AppConfig {
|
||||
|
||||
public List<String> getVideoUris() { return videoUris; }
|
||||
public void setVideoUris(List<String> uris) { this.videoUris = uris; }
|
||||
|
||||
/**
|
||||
* 检查是否有可用的媒体源(文件夹、图片或视频)
|
||||
*/
|
||||
public boolean hasMedia() {
|
||||
boolean hasFolders = selectedFolders != null && !selectedFolders.isEmpty();
|
||||
boolean hasImages = imageUris != null && !imageUris.isEmpty();
|
||||
boolean hasVideos = videoEnabled && videoUris != null && !videoUris.isEmpty();
|
||||
return hasFolders || hasImages || hasVideos;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,16 @@
|
||||
package cn.hugh.bz.gk2.model;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
public enum MediaType {
|
||||
IMAGE,
|
||||
VIDEO;
|
||||
|
||||
public static final List<String> IMAGE_EXTENSIONS = Arrays.asList("jpg", "jpeg", "png", "webp", "bmp", "heic", "heif");
|
||||
public static final List<String> VIDEO_EXTENSIONS = Arrays.asList("mp4", "webm", "3gp", "mkv", "avi", "mov", "flv");
|
||||
|
||||
public boolean isImage() {
|
||||
return this == IMAGE;
|
||||
}
|
||||
@@ -11,4 +18,28 @@ public enum MediaType {
|
||||
public boolean isVideo() {
|
||||
return this == VIDEO;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据文件名或 URI 判断媒体类型
|
||||
*/
|
||||
public static MediaType fromUri(String uri) {
|
||||
if (uri == null) return null;
|
||||
String lowerUri = uri.toLowerCase(Locale.ROOT);
|
||||
|
||||
// Simple extension check
|
||||
for (String ext : VIDEO_EXTENSIONS) {
|
||||
if (lowerUri.endsWith("." + ext)) {
|
||||
return VIDEO;
|
||||
}
|
||||
}
|
||||
|
||||
for (String ext : IMAGE_EXTENSIONS) {
|
||||
if (lowerUri.endsWith("." + ext)) {
|
||||
return IMAGE;
|
||||
}
|
||||
}
|
||||
|
||||
// Default fallback (can be improved)
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -299,24 +299,29 @@ public class AlbumManagementFragment extends Fragment {
|
||||
int directVideoCount = album.getVideoUris() != null ? album.getVideoUris().size() : 0;
|
||||
int directMediaCount = directImageCount + directVideoCount;
|
||||
|
||||
// 总数量 = 直接添加的 + 文件夹中的(异步计算)
|
||||
tvAlbumInfo.setText(folderCount + " 个文件夹 · " + directMediaCount + " 个文件");
|
||||
// 相册信息(文件夹数量和直接添加的媒体数量)
|
||||
tvAlbumInfo.setText(album.getMediaSummary());
|
||||
|
||||
// 异步计算文件夹中的媒体数量
|
||||
// 异步计算文件夹中的媒体数量并显示更详细的信息
|
||||
if (folderCount > 0) {
|
||||
new Thread(() -> {
|
||||
MediaScanner scanner = new MediaScanner(context);
|
||||
int totalMedia = directMediaCount;
|
||||
int totalImages = directImageCount;
|
||||
int totalVideos = directVideoCount;
|
||||
|
||||
for (String folder : album.getFolders()) {
|
||||
List<WallpaperMedia> mediaList = scanner.scanFolder(folder);
|
||||
totalMedia += mediaList.size();
|
||||
for (WallpaperMedia m : mediaList) {
|
||||
if (m.isVideo()) totalVideos++;
|
||||
else totalImages++;
|
||||
}
|
||||
}
|
||||
final int finalTotal = totalMedia;
|
||||
|
||||
final String summary = folderCount + " 个文件夹 · " + totalImages + " 张图片 · " + totalVideos + " 个视频";
|
||||
|
||||
// 更新 UI
|
||||
if (tvAlbumInfo != null) {
|
||||
tvAlbumInfo.post(() ->
|
||||
tvAlbumInfo.setText(folderCount + " 个文件夹 · " + finalTotal + " 个文件")
|
||||
);
|
||||
tvAlbumInfo.post(() -> tvAlbumInfo.setText(summary));
|
||||
}
|
||||
scanner.shutdown();
|
||||
}).start();
|
||||
|
||||
@@ -89,7 +89,7 @@ public class HomeFragment extends Fragment {
|
||||
}
|
||||
|
||||
private void toggleService() {
|
||||
if (config.getSelectedFolders().isEmpty() && (config.getImageUris() == null || config.getImageUris().isEmpty())) {
|
||||
if (!config.hasMedia()) {
|
||||
Toast.makeText(requireContext(), "请先在相册页面添加文件夹或图片", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
@@ -185,8 +185,8 @@ public class HomeFragment extends Fragment {
|
||||
android.util.Log.i(TAG, "Image URIs count: " + imageCount);
|
||||
cn.hugh.bz.gk2.utils.FileLogger.getInstance(requireContext()).log(TAG, "Image URIs count: " + imageCount);
|
||||
|
||||
if (config.getSelectedFolders().isEmpty() && (imageUris == null || imageUris.isEmpty())) {
|
||||
android.util.Log.w(TAG, "No folders or images selected, showing toast");
|
||||
if (!config.hasMedia()) {
|
||||
android.util.Log.w(TAG, "No media available, showing toast");
|
||||
Toast.makeText(requireContext(), "请先在相册页面添加文件夹或图片", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
@@ -275,13 +275,10 @@ public class HomeFragment extends Fragment {
|
||||
Album activeAlbum = albumPrefs.getActiveAlbum();
|
||||
if (activeAlbum != null) {
|
||||
tvAlbumName.setText(activeAlbum.getName());
|
||||
|
||||
int folderCount = activeAlbum.getFolders() != null ? activeAlbum.getFolders().size() : 0;
|
||||
int imageCount = folderCount;
|
||||
tvAlbumInfo.setText(folderCount + " 个文件夹 · " + imageCount + " 张图片");
|
||||
tvAlbumInfo.setText(activeAlbum.getMediaSummary());
|
||||
} else {
|
||||
tvAlbumName.setText("默认相册");
|
||||
tvAlbumInfo.setText("0 个文件夹 · 0 张图片");
|
||||
tvAlbumInfo.setText("无媒体内容");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,8 +24,7 @@ import cn.hugh.bz.gk2.model.WallpaperMedia;
|
||||
|
||||
public class MediaScanner {
|
||||
private static final String TAG = "MediaScanner";
|
||||
private static final List<String> IMAGE_EXTENSIONS = List.of("jpg", "jpeg", "png", "webp", "bmp");
|
||||
private static final List<String> VIDEO_EXTENSIONS = List.of("mp4", "webm", "3gp", "mkv", "avi", "mov", "flv");
|
||||
// Extensions are now central in MediaType
|
||||
|
||||
// 性能优化:限制单次扫描的最大文件数
|
||||
private static final int MAX_SCAN_COUNT = 50000;
|
||||
@@ -308,9 +307,9 @@ public class MediaScanner {
|
||||
private MediaType getMediaType(String fileName) {
|
||||
if (fileName == null) return null;
|
||||
String ext = getExtension(fileName).toLowerCase();
|
||||
if (IMAGE_EXTENSIONS.contains(ext)) {
|
||||
if (MediaType.IMAGE_EXTENSIONS.contains(ext)) {
|
||||
return MediaType.IMAGE;
|
||||
} else if (VIDEO_EXTENSIONS.contains(ext)) {
|
||||
} else if (MediaType.VIDEO_EXTENSIONS.contains(ext)) {
|
||||
return MediaType.VIDEO;
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -123,6 +123,7 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
private boolean isPlayingVideo = false;
|
||||
private volatile boolean isLoadingWallpaper = false; // 防止重复加载
|
||||
private boolean isCharging = true; // Default to charging to avoid pausing initially
|
||||
private boolean changeOnReturn = false; // 标志:是否因返回桌面而需要更换壁纸
|
||||
|
||||
public void handleBatteryChanged(boolean isCharging) {
|
||||
this.isCharging = isCharging;
|
||||
@@ -158,6 +159,8 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
@Override
|
||||
public void onPrepared() {
|
||||
Log.i(TAG, "Video prepared and playing");
|
||||
// 视频准备完成,现在可以接受新的加载请求
|
||||
isLoadingWallpaper = false;
|
||||
// Check battery status immediately after start to handle "pause on battery" policy
|
||||
// while still ensuring the first frame is rendered
|
||||
handler.post(() -> checkBatteryAndPauseIfNeeded());
|
||||
@@ -166,7 +169,13 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
@Override
|
||||
public void onError(String error) {
|
||||
Log.e(TAG, "Video error: " + error);
|
||||
handler.post(() -> drawWallpaper());
|
||||
// 视频加载失败,允许新的加载请求
|
||||
isLoadingWallpaper = false;
|
||||
// CRITICAL FIX: Do NOT call drawWallpaper() here.
|
||||
// This causes infinite loops if the video keeps failing.
|
||||
// Instead, just log it. The user will see a black screen or the last frame,
|
||||
// which is better than a battery-draining loop.
|
||||
fileLogger.error(TAG, "Video player error occurred: " + error, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -189,8 +198,8 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
public void onCreate(android.view.SurfaceHolder surfaceHolder) {
|
||||
super.onCreate(surfaceHolder);
|
||||
|
||||
// Set pixel format to support media player
|
||||
surfaceHolder.setFormat(android.graphics.PixelFormat.TRANSLUCENT);
|
||||
// Use OPAQUE for better MediaPlayer compatibility
|
||||
surfaceHolder.setFormat(android.graphics.PixelFormat.OPAQUE);
|
||||
|
||||
// 更新服务活跃时间
|
||||
WallpaperServiceHelper.updateActiveTime(AutoWallpaperService.this);
|
||||
@@ -208,38 +217,48 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
|
||||
// 更新 VideoPlayer 的 Surface,确保视频能正确渲染
|
||||
videoPlayer.setSurface(holder.getSurface());
|
||||
|
||||
if (visible) {
|
||||
drawWallpaper();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onVisibilityChanged(boolean visible) {
|
||||
super.onVisibilityChanged(visible);
|
||||
this.visible = visible;
|
||||
@Override
|
||||
public void onVisibilityChanged(boolean visible) {
|
||||
super.onVisibilityChanged(visible);
|
||||
this.visible = visible;
|
||||
|
||||
// 当壁纸可见时,更新活跃时间
|
||||
if (visible) {
|
||||
WallpaperServiceHelper.updateActiveTime(AutoWallpaperService.this);
|
||||
if (isPlayingVideo) {
|
||||
AppConfig config = prefs.loadConfig();
|
||||
if (config.isVideoPauseOnBattery() && !isCharging) {
|
||||
// Do not resume if on battery and pause on battery is enabled
|
||||
fileLogger.log(TAG, "Video remains paused (visible but on battery)");
|
||||
} else {
|
||||
videoPlayer.resume();
|
||||
fileLogger.log(TAG, "Video resumed");
|
||||
}
|
||||
}
|
||||
drawWallpaper();
|
||||
} else {
|
||||
if (isPlayingVideo) {
|
||||
videoPlayer.pause();
|
||||
fileLogger.log(TAG, "Video paused (not visible)");
|
||||
}
|
||||
}
|
||||
}
|
||||
// 当壁纸可见时,更新活跃时间
|
||||
if (visible) {
|
||||
WallpaperServiceHelper.updateActiveTime(AutoWallpaperService.this);
|
||||
|
||||
// 设置返回桌面标志(如果配置启用了该功能)
|
||||
AppConfig config = prefs.loadConfig();
|
||||
if (config.isChangeOnReturnToHome()) {
|
||||
changeOnReturn = true;
|
||||
}
|
||||
|
||||
// CRITICAL FIX: Do NOT resume video if we are about to change it.
|
||||
// Resume ONLY if we are sticking with the current wallpaper.
|
||||
if (isPlayingVideo && !changeOnReturn && !forceChangeNext && !scheduledNext) {
|
||||
if (config.isVideoPauseOnBattery() && !isCharging) {
|
||||
fileLogger.log(TAG, "Video remains paused (visible but on battery)");
|
||||
} else {
|
||||
videoPlayer.resume();
|
||||
fileLogger.log(TAG, "Video resumed");
|
||||
}
|
||||
}
|
||||
|
||||
drawWallpaper();
|
||||
} else {
|
||||
if (isPlayingVideo) {
|
||||
videoPlayer.pause();
|
||||
fileLogger.log(TAG, "Video paused (not visible)");
|
||||
}
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void onSurfaceDestroyed(android.view.SurfaceHolder holder) {
|
||||
super.onSurfaceDestroyed(holder);
|
||||
@@ -308,7 +327,7 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
boolean shouldChange = false;
|
||||
|
||||
String statusMsg = "drawWallpaper: forceChangeNext=" + forceChangeNext + ", scheduledNext=" + scheduledNext +
|
||||
", changeOnReturn=" + config.isChangeOnReturnToHome();
|
||||
", changeOnReturn=" + changeOnReturn;
|
||||
Log.i(TAG, statusMsg);
|
||||
fileLogger.log(TAG, statusMsg);
|
||||
|
||||
@@ -318,7 +337,7 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
} else if (scheduledNext) {
|
||||
shouldChange = true;
|
||||
fileLogger.log(TAG, "Scheduled change");
|
||||
} else if (config.isChangeOnReturnToHome()) {
|
||||
} else if (changeOnReturn) {
|
||||
shouldChange = true;
|
||||
fileLogger.log(TAG, "Change on return to home");
|
||||
}
|
||||
@@ -327,6 +346,7 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
final boolean needChange = shouldChange;
|
||||
forceChangeNext = false;
|
||||
scheduledNext = false;
|
||||
changeOnReturn = false; // 重置返回桌面标志
|
||||
|
||||
// 如果不需要更换且有缓存,保持当前媒体
|
||||
if (!needChange && currentMedia != null) {
|
||||
@@ -351,9 +371,10 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
isLoadingWallpaper = true;
|
||||
handler.post(() -> {
|
||||
stopImageDisplay();
|
||||
// clearSurface();
|
||||
playVideo(lastMedia, config);
|
||||
currentMedia = lastMedia;
|
||||
isLoadingWallpaper = false;
|
||||
// 注意:isLoadingWallpaper 将在 onPrepared 或 onError 回调中设置为 false
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -386,18 +407,15 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
if (media.isVideo()) {
|
||||
handler.post(() -> {
|
||||
stopImageDisplay();
|
||||
// clearSurface();
|
||||
playVideo(media, config);
|
||||
currentMedia = media;
|
||||
|
||||
prefs.saveConfig(config);
|
||||
prefs.saveLastUri(media.getUri());
|
||||
|
||||
isLoadingWallpaper = false;
|
||||
|
||||
// Check if another update is pending
|
||||
if (forceChangeNext || scheduledNext) {
|
||||
drawWallpaper();
|
||||
}
|
||||
// 注意:isLoadingWallpaper 将在 onPrepared 或 onError 回调中设置为 false
|
||||
// 不在这里检查 pending updates,因为视频还在准备中
|
||||
});
|
||||
} else {
|
||||
// 在后台线程加载图片
|
||||
@@ -653,6 +671,22 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Filter based on configuration
|
||||
if (!config.isVideoEnabled()) {
|
||||
List<WallpaperMedia> filtered = new ArrayList<>();
|
||||
for (WallpaperMedia m : allMedia) {
|
||||
if (!m.isVideo()) {
|
||||
filtered.add(m);
|
||||
}
|
||||
}
|
||||
if (allMedia.size() != filtered.size()) {
|
||||
String filterMsg = "Filtered out " + (allMedia.size() - filtered.size()) + " videos (video disabled)";
|
||||
Log.i(TAG, filterMsg);
|
||||
fileLogger.log(TAG, filterMsg);
|
||||
}
|
||||
allMedia = filtered;
|
||||
}
|
||||
|
||||
String msg = "getNextMedia: playMode=" + config.getPlayMode() + ", totalMedia=" + allMedia.size() +
|
||||
", folders=" + (folders != null ? folders.size() : 0) +
|
||||
", directImages=" + (imageUris != null ? imageUris.size() : 0) +
|
||||
@@ -780,6 +814,29 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
}
|
||||
}
|
||||
|
||||
private void clearSurface() {
|
||||
SurfaceHolder holder = getSurfaceHolder();
|
||||
if (holder != null && holder.getSurface().isValid()) {
|
||||
Canvas canvas = null;
|
||||
try {
|
||||
canvas = holder.lockCanvas();
|
||||
if (canvas != null) {
|
||||
canvas.drawColor(Color.TRANSPARENT, android.graphics.PorterDuff.Mode.CLEAR);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error clearing surface", e);
|
||||
} finally {
|
||||
if (canvas != null) {
|
||||
try {
|
||||
holder.unlockCanvasAndPost(canvas);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error unlocking canvas", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasAvailableMedia(AppConfig config) {
|
||||
boolean hasFolders = config.getSelectedFolders() != null && !config.getSelectedFolders().isEmpty();
|
||||
boolean hasImages = config.getImageUris() != null && !config.getImageUris().isEmpty();
|
||||
@@ -798,8 +855,13 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
if (!config.isVideoEnabled() || uri == null) {
|
||||
return false;
|
||||
}
|
||||
// 1. Check if it's in the manual video list
|
||||
List<String> videoUris = config.getVideoUris();
|
||||
return videoUris != null && videoUris.contains(uri);
|
||||
if (videoUris != null && videoUris.contains(uri)) {
|
||||
return true;
|
||||
}
|
||||
// 2. Check file extension
|
||||
return MediaType.fromUri(uri) == MediaType.VIDEO;
|
||||
}
|
||||
|
||||
private WallpaperMedia buildMediaFromUri(AppConfig config, String uri) {
|
||||
|
||||
@@ -6,6 +6,8 @@ import android.net.Uri;
|
||||
import android.util.Log;
|
||||
import android.view.Surface;
|
||||
|
||||
import cn.hugh.bz.gk2.utils.FileLogger;
|
||||
|
||||
public class VideoPlayer {
|
||||
private static final String TAG = "VideoPlayer";
|
||||
|
||||
@@ -18,9 +20,11 @@ public class VideoPlayer {
|
||||
private MediaPlayer mediaPlayer;
|
||||
private Surface surface;
|
||||
private boolean isPrepared = false;
|
||||
private boolean hasError = false; // 追踪错误状态,防止在错误状态下操作
|
||||
private VideoPlayerCallback callback;
|
||||
private float volume = 0f;
|
||||
private VideoScaleType scaleType = VideoScaleType.CENTER_CROP;
|
||||
private FileLogger fileLogger;
|
||||
|
||||
public interface VideoPlayerCallback {
|
||||
void onPrepared();
|
||||
@@ -30,8 +34,11 @@ public class VideoPlayer {
|
||||
|
||||
public void setSurface(Surface surface) {
|
||||
this.surface = surface;
|
||||
if (mediaPlayer != null) {
|
||||
// 只在已准备好且没有错误时才设置 Surface
|
||||
// 避免在 prepareAsync 过程中或错误状态下设置 Surface
|
||||
if (mediaPlayer != null && isPrepared && !hasError) {
|
||||
mediaPlayer.setSurface(surface);
|
||||
if (fileLogger != null) fileLogger.log(TAG, "setSurface called (external)");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,26 +47,46 @@ public class VideoPlayer {
|
||||
}
|
||||
|
||||
public void play(Context context, String uri) {
|
||||
if (fileLogger == null) {
|
||||
fileLogger = FileLogger.getInstance(context);
|
||||
}
|
||||
release();
|
||||
Log.i(TAG, "Playing video: " + uri);
|
||||
hasError = false; // 重置错误状态
|
||||
fileLogger.log(TAG, "play() called with URI: " + uri);
|
||||
|
||||
try {
|
||||
mediaPlayer = new MediaPlayer();
|
||||
mediaPlayer.setDataSource(context, Uri.parse(uri));
|
||||
if (surface != null) {
|
||||
mediaPlayer.setSurface(surface);
|
||||
mediaPlayer.reset();
|
||||
|
||||
Uri contentUri = Uri.parse(uri);
|
||||
|
||||
// Try to set data source
|
||||
try {
|
||||
mediaPlayer.setDataSource(context, contentUri);
|
||||
} catch (Exception e) {
|
||||
fileLogger.error(TAG, "setDataSource failed", e);
|
||||
throw e;
|
||||
}
|
||||
|
||||
mediaPlayer.setLooping(true);
|
||||
mediaPlayer.setVolume(volume, volume);
|
||||
|
||||
mediaPlayer.setOnPreparedListener(mp -> {
|
||||
if (mediaPlayer != mp) {
|
||||
Log.w(TAG, "Ignoring onPrepared from stale MediaPlayer");
|
||||
fileLogger.warn(TAG, "Ignoring onPrepared from stale MediaPlayer");
|
||||
return;
|
||||
}
|
||||
isPrepared = true;
|
||||
|
||||
// Apply scaling mode
|
||||
// DELAYED SURFACE ATTACHMENT:
|
||||
// Attach surface now in onPrepared
|
||||
if (surface != null && surface.isValid()) {
|
||||
mp.setSurface(surface);
|
||||
fileLogger.log(TAG, "setSurface called in onPrepared");
|
||||
} else {
|
||||
fileLogger.warn(TAG, "Surface invalid or null in onPrepared");
|
||||
}
|
||||
|
||||
if (scaleType == VideoScaleType.CENTER_CROP) {
|
||||
mp.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
|
||||
} else {
|
||||
@@ -68,7 +95,7 @@ public class VideoPlayer {
|
||||
|
||||
mp.setVolume(volume, volume);
|
||||
mp.start();
|
||||
Log.i(TAG, "Video prepared and started");
|
||||
fileLogger.log(TAG, "Video prepared and started");
|
||||
if (callback != null) {
|
||||
callback.onPrepared();
|
||||
}
|
||||
@@ -76,10 +103,12 @@ public class VideoPlayer {
|
||||
|
||||
mediaPlayer.setOnErrorListener((mp, what, extra) -> {
|
||||
if (mediaPlayer != mp) {
|
||||
Log.w(TAG, "Ignoring onError from stale MediaPlayer");
|
||||
fileLogger.warn(TAG, "Ignoring onError from stale MediaPlayer");
|
||||
return true;
|
||||
}
|
||||
Log.e(TAG, "MediaPlayer error: what=" + what + ", extra=" + extra);
|
||||
hasError = true; // 标记错误状态,防止后续 resume/pause 操作
|
||||
isPrepared = false; // 错误后不再视为已准备
|
||||
fileLogger.log(TAG, "MediaPlayer error: what=" + what + ", extra=" + extra);
|
||||
if (callback != null) {
|
||||
callback.onError("Playback error: " + what);
|
||||
}
|
||||
@@ -88,19 +117,20 @@ public class VideoPlayer {
|
||||
|
||||
mediaPlayer.setOnCompletionListener(mp -> {
|
||||
if (mediaPlayer != mp) {
|
||||
Log.w(TAG, "Ignoring onCompletion from stale MediaPlayer");
|
||||
fileLogger.warn(TAG, "Ignoring onCompletion from stale MediaPlayer");
|
||||
return;
|
||||
}
|
||||
Log.i(TAG, "Video completed");
|
||||
fileLogger.log(TAG, "Video completed");
|
||||
if (callback != null) {
|
||||
callback.onCompletion();
|
||||
}
|
||||
});
|
||||
|
||||
mediaPlayer.prepareAsync();
|
||||
Log.i(TAG, "Starting async prepare for: " + uri);
|
||||
fileLogger.log(TAG, "Starting async prepare for: " + uri);
|
||||
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error playing video", e);
|
||||
fileLogger.error(TAG, "Error playing video", e);
|
||||
if (callback != null) {
|
||||
callback.onError(e.getMessage());
|
||||
}
|
||||
@@ -108,16 +138,16 @@ public class VideoPlayer {
|
||||
}
|
||||
|
||||
public void pause() {
|
||||
if (mediaPlayer != null && isPrepared && mediaPlayer.isPlaying()) {
|
||||
if (mediaPlayer != null && isPrepared && !hasError && mediaPlayer.isPlaying()) {
|
||||
mediaPlayer.pause();
|
||||
Log.i(TAG, "Video paused");
|
||||
if (fileLogger != null) fileLogger.log(TAG, "Video paused");
|
||||
}
|
||||
}
|
||||
|
||||
public void resume() {
|
||||
if (mediaPlayer != null && isPrepared && !mediaPlayer.isPlaying()) {
|
||||
if (mediaPlayer != null && isPrepared && !hasError && !mediaPlayer.isPlaying()) {
|
||||
mediaPlayer.start();
|
||||
Log.i(TAG, "Video resumed");
|
||||
if (fileLogger != null) fileLogger.log(TAG, "Video resumed");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,17 +158,18 @@ public class VideoPlayer {
|
||||
mediaPlayer.stop();
|
||||
}
|
||||
mediaPlayer.release();
|
||||
Log.i(TAG, "MediaPlayer released");
|
||||
if (fileLogger != null) fileLogger.log(TAG, "MediaPlayer released");
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error releasing MediaPlayer", e);
|
||||
if (fileLogger != null) fileLogger.error(TAG, "Error releasing MediaPlayer", e);
|
||||
}
|
||||
mediaPlayer = null;
|
||||
isPrepared = false;
|
||||
hasError = false; // 重置错误状态
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isPlaying() {
|
||||
return mediaPlayer != null && isPrepared && mediaPlayer.isPlaying();
|
||||
return mediaPlayer != null && isPrepared && !hasError && mediaPlayer.isPlaying();
|
||||
}
|
||||
|
||||
public void setVolume(float volume) {
|
||||
|
||||
Reference in new issue
Block a user