package com.example.chemical.utils; import android.media.MediaPlayer; import android.util.Log; import com.blankj.utilcode.util.LogUtils; import com.blankj.utilcode.util.Utils; /** * 播放音频 */ public class AudioPlayer { private static AudioPlayer instance; private MediaPlayer mediaPlayer; private int currentAudioResId = 0; private AudioPlayer() { // 私有构造函数,防止外部创建实例 } public static synchronized AudioPlayer getInstance() { if (instance == null) { instance = new AudioPlayer(); } return instance; } public void play(int audioResId) { if (mediaPlayer != null && currentAudioResId == audioResId) { if (!mediaPlayer.isPlaying()) { mediaPlayer.start(); } return; } stop(); try { mediaPlayer = MediaPlayer.create(Utils.getApp(), audioResId); if (mediaPlayer != null) { mediaPlayer.start(); currentAudioResId = audioResId; mediaPlayer.setOnCompletionListener(mp -> stop()); } else { LogUtils.e("Failed to create MediaPlayer for resource ID: " + audioResId); } } catch (Exception e) { LogUtils.e("Error playing audio resource: " + audioResId, Log.getStackTraceString(e)); } } public void stop() { if (mediaPlayer != null) { if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); } mediaPlayer.release(); mediaPlayer = null; currentAudioResId = 0; } } public boolean isPlaying() { return mediaPlayer != null && mediaPlayer.isPlaying(); } }