用MediaPlayer实现自定义声音,本来是不需要先把mediaplayer置空的,但是如果需要连续播放声音的时候,会出现隔一段时间(应该是音频的长度)才成功调用一次,而我需要的是后边的调用会覆盖前边的,也就是短时间多次调用会在最后完整的播放;本来想通过mediaPlayer.stop()方法来停止之前的调用,但是没有效果。
public class SoundUtil {
private static final String TAG = "SoundUtil";
private static MediaPlayer mediaPlayer = null;
public static void playSound(Context context) {
try {
if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
mediaPlayer = MediaPlayer.create(context, R.raw.beep);
mediaPlayer.start();
} catch (Exception ex) {
ex.printStackTrace();
Log.e(TAG, "playSound_Ex: " + ex.getMessage());
}
}
public static void relaseMediaPlayer() {
if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
}
}
在网上看到另一种方法:
原文地址:http://blog.csdn.net/rzleilei/article/details/17792437
private static Ringtone ring;
//将自定义声音当做铃声播放
public static void playNotify(Context context) {
if (ring == null) {
String uri = "android.resource://" + context.getPackageName() + "/" + R.raw.notify;
Uri no = Uri.parse(uri);
ring = RingtoneManager.getRingtone(context, no);
}
if (ring.isPlaying()) {
ring.stop();
}
ring.play();
}