Android 播放音频工具类
1 import android.content.Context; 2 import android.media.AudioManager; 3 import android.media.MediaPlayer; 4 import android.os.Handler; 5 import android.os.Message; 6 7 import java.io.IOException; 8 9 public class MediaPlayerUitls { 10 11 private static MediaPlayer mediaPlayer; 12 13 14 public static void build(){ 15 mediaPlayer = new MediaPlayer(); 16 } 17 18 19 public static void startMadieMusic(Context context, Object path, final Handler handler){ 20 try { 21 playAllStop(); 22 if(path instanceof String){ 23 mediaPlayer = new MediaPlayer(); 24 mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); 25 mediaPlayer.setDataSource(String.valueOf(path)); 26 mediaPlayer.prepareAsync(); 27 }else if(path instanceof Integer){ 28 if(((Integer) path)==0){ 29 if(BuildConfig.DEBUG){ 30 Message message = new Message(); 31 message.what = 2; 32 message.obj = "声音null"; 33 if(handler!=null) 34 handler.sendMessage(message); 35 } 36 return; 37 } 38 mediaPlayer = MediaPlayer.create(context, (Integer) path); 39 mediaPlayer.start(); 40 if(handler!=null) 41 handler.sendEmptyMessage(0); 42 } 43 44 mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { 45 @Override 46 public void onPrepared(MediaPlayer mediaPlayer) { 47 try { 48 mediaPlayer.start(); 49 if(mediaPlayer.isPlaying()){ 50 if(handler!=null) 51 handler.sendEmptyMessage(0); 52 } 53 }catch (Exception e){ 54 //Throws: 55 //IllegalStateException – 56 // if the internal player engine has not been initialized or has been released. 57 } 58 } 59 }); 60 mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 61 @Override 62 public void onCompletion(MediaPlayer mp) { 63 if(handler!=null) 64 handler.sendEmptyMessage(1); 65 } 66 }); 67 68 mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { 69 @Override 70 public boolean onError(MediaPlayer mp, int what, int extra) { 71 Message message = new Message(); 72 message.what = 2; 73 message.obj = extra; 74 if(handler!=null) 75 handler.sendMessage(message); 76 return false; 77 } 78 }); 79 mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() { 80 @Override 81 public void onBufferingUpdate(MediaPlayer mp, int percent) { 82 83 } 84 }); 85 } catch (Exception e) { 86 e.printStackTrace(); 87 } 88 } 89 90 public static void playStop() { 91 92 if (mediaPlayer != null) { 93 if (mediaPlayer.isPlaying()) { 94 mediaPlayer.stop(); 95 } 96 mediaPlayer.release(); 97 mediaPlayer = null; 98 } 99 } 100 101 public static void playAllStop(){ 102 synchronized (MediaUitl.class){ 103 playStop(); 104 } 105 } 106 }
调用: MediaPlayerUitls.startMadieMusic(requireContext(),R.raw.raw_no_install_no_use,null)