Android播放音訊工具類
阿新 • • 發佈:2018-12-31
播放完畢重置mediaplayer,播放完畢才能播放下一次。播放小音訊建議使用soundpool(音訊大小不超過900k)
public class PlayMusicUtils { private static MediaPlayer mediaPlayer; public static void playSound(Activity activity, int resId) { activity.setVolumeControlStream(AudioManager.STREAM_MUSIC); if (mediaPlayer == null) { mediaPlayer= new MediaPlayer(); } if (mediaPlayer.isPlaying()) { return; } mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setOnCompletionListener( new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { mediaPlayer.reset();} } ); AssetFileDescriptor file = activity.getResources().openRawResourceFd(resId); try { mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength()); file.close(); mediaPlayer.setVolume(0.1f, 0.1f); mediaPlayer.prepare(); } catch(Exception e) { mediaPlayer = null; e.printStackTrace(); } if (mediaPlayer != null) { mediaPlayer.start(); } } }