点击按钮播放声音简单实现。

来源:互联网 发布:淘宝去哪里看分销后台 编辑:程序博客网 时间:2024/05/16 19:06


用户与android界面交互时,界面会以各种方式表达回应,比如一个动画,或者播放一段音频。

这里简单实现了当用户点击按钮的时候,播放声音。

只贴上一部分代码,如有兴趣可以自己实现下。


package com.example.sqlitepagetest;import java.util.HashMap;import android.content.Context;import android.media.AudioManager;import android.media.SoundPool;import android.util.Log;public class MySoundPool {public static SoundPool mSoundPool = null;public static HashMap<String, Integer> mSoundPoolMap = null;public static void initSoundPool(Context context) {if (mSoundPool == null) {// public SoundPool(int maxStream, int streamType, int srcQuality)// maxStream —— 同时播放的流的最大数量// streamType —— 流的类型,一般为STREAM_MUSIC(具体在AudioManager类中列出)// srcQuality —— 采样率转化质量,当前无效果,使用0作为默认值eg.mSoundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 5);mSoundPoolMap = new HashMap<String, Integer>();// 需要的时候再开放// mSoundPoolMap.put("keyloud",// mSoundPool.load(context, R.raw.keyloud, 5));// mSoundPoolMap.put("keypress",// mSoundPool.load(context, R.raw.keypress, 5));// mSoundPoolMap.put("staffcall",// mSoundPool.load(context, R.raw.staffcall, 5));mSoundPoolMap.put("soundtest",mSoundPool.load(context, R.raw.test, 5));}}public static void play(Context context, String src) {if (mSoundPoolMap == null || !mSoundPoolMap.containsKey(src)&& mSoundPoolMap.get(src) == null || mSoundPool == null) {// 设置缺省mSoundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 5);mSoundPoolMap = new HashMap<String, Integer>();mSoundPoolMap.put("soundtest",mSoundPool.load(context, R.raw.test, 5));mSoundPool.play(mSoundPoolMap.get(src), 1, 1, 1, 0, 1.0f);return;}int result = mSoundPool.play(mSoundPoolMap.get(src), 1, 1, 1, 0, 1.0f);if (result == 0) {Log.e("---------------", "播放SoundPool失败->" + src);return;} else {Log.e("---------------", "播放SoundPool成功->" + src);}}public static void play(String src) {play(Application_my.mContext, src);}/** * 遍历释放sound资源 */public static void clear() {if (mSoundPoolMap != null) {// 释放HashMap中的所有元素.mSoundPoolMap.clear();if (mSoundPool != null) {mSoundPool.release();}}}}

这个类在刚进入应用的时候,就加载好声音文件。然后在按钮事件触发的位置(通常在onClick()方法中)MySoundPool.play("mySoundName");

即可。

0 0
原创粉丝点击