用MediaPlayer實現(xiàn)自定義聲音,本來是不需要先把mediaplayer置空的榜聂,但是如果需要連續(xù)播放聲音的時候耀怜,會出現(xiàn)隔一段時間(應(yīng)該是音頻的長度)才成功調(diào)用一次,而我需要的是后邊的調(diào)用會覆蓋前邊的,也就是短時間多次調(diào)用會在最后完整的播放耳璧;本來想通過mediaPlayer.stop()方法來停止之前的調(diào)用辅鲸,但是沒有效果格郁。
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;
}
}
}
在網(wǎng)上看到另一種方法:
原文地址:http://blog.csdn.net/rzleilei/article/details/17792437
private static Ringtone ring;
//將自定義聲音當(dāng)做鈴聲播放
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();
}