AudioPlayer.java 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package com.example.chemical.utils;
  2. import android.media.MediaPlayer;
  3. import android.util.Log;
  4. import com.blankj.utilcode.util.LogUtils;
  5. import com.blankj.utilcode.util.Utils;
  6. /**
  7. * 播放音频
  8. */
  9. public class AudioPlayer {
  10. private static AudioPlayer instance;
  11. private MediaPlayer mediaPlayer;
  12. private int currentAudioResId = 0;
  13. private AudioPlayer() {
  14. // 私有构造函数,防止外部创建实例
  15. }
  16. public static synchronized AudioPlayer getInstance() {
  17. if (instance == null) {
  18. instance = new AudioPlayer();
  19. }
  20. return instance;
  21. }
  22. public void play(int audioResId) {
  23. if (mediaPlayer != null && currentAudioResId == audioResId) {
  24. if (!mediaPlayer.isPlaying()) {
  25. mediaPlayer.start();
  26. }
  27. return;
  28. }
  29. stop();
  30. try {
  31. mediaPlayer = MediaPlayer.create(Utils.getApp(), audioResId);
  32. if (mediaPlayer != null) {
  33. mediaPlayer.start();
  34. currentAudioResId = audioResId;
  35. mediaPlayer.setOnCompletionListener(mp -> stop());
  36. } else {
  37. LogUtils.e("Failed to create MediaPlayer for resource ID: " + audioResId);
  38. }
  39. } catch (Exception e) {
  40. LogUtils.e("Error playing audio resource: " + audioResId, Log.getStackTraceString(e));
  41. }
  42. }
  43. public void stop() {
  44. if (mediaPlayer != null) {
  45. if (mediaPlayer.isPlaying()) {
  46. mediaPlayer.stop();
  47. }
  48. mediaPlayer.release();
  49. mediaPlayer = null;
  50. currentAudioResId = 0;
  51. }
  52. }
  53. public boolean isPlaying() {
  54. return mediaPlayer != null && mediaPlayer.isPlaying();
  55. }
  56. }