简单记录,非常简单的一个提示音播放类(允许多个提示音播放)

本文介绍了一个用于Android平台的音频播放组件实现,包括使用MediaPlayer播放提示音及SoundPool播放短小音效的方法。MediaPlayer通过创建实例并加载资源ID来播放音频文件,而SoundPool则适用于播放较小的声音文件。
import java.io.File;
import java.io.IOException;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;

/**
 * @author maclay
 * 
 *         mediaplayer用来播放提示音,需要提供音频文件id
 * 
 *         2013-5-13
 */
public class AlertTone {
	private MediaPlayer mPlayer = null;
	static AlertTone smAlertTone;

	public static AlertTone getInstance() {
		if (smAlertTone == null) {
			smAlertTone = new AlertTone();
		}
		return smAlertTone;
	}

	public void play(Context context, int id) {
		if (mPlayer == null) {
			mPlayer = MediaPlayer.create(context, id);
		}
		if (mPlayer.isPlaying()) {
			System.out.println(11111);
			return;
		}
		try {
			mPlayer.start();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}
		mPlayer.setOnCompletionListener(new OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer mp) {
				mp.release();
				mPlayer=null;
				smAlertTone=null;
			}
		});
	}
}
//使用soundpool


public class WorksheetSoundPool {
	private SoundPool mSoundPool;
	public static WorksheetSoundPool smPool;
	private int mID;

	public static WorksheetSoundPool getInstance() {
		if (smPool == null) {
			smPool = new WorksheetSoundPool();
		}
		return smPool;
	}

	public void play() {
		if (mSoundPool == null) {
			mSoundPool = new SoundPool(3, 1, 0);
			mID = mSoundPool.load(PttApplication.getAppContext(), R.raw.msg, 1);
			mSoundPool.setLoop(mID, 0);
		}
		mSoundPool.play(mID, 10, 10, 0, 0, 1f);
	}

	public void close() {
		if (mSoundPool != null) {
			try {
				mSoundPool.release();
			} catch (Exception e) {
			}
			mSoundPool = null;
		}
		smPool = null;
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值