1,在res/raw中加入mp3文件
2,实现播放类
import android.content.Context;import android.media.AudioManager;import android.media.SoundPool;import android.util.Log;import java.util.HashMap;import java.util.Map;public class UtilSound {public static SoundPool sp;public static Map suondMap;public static Context context;public static int SOUND_DI = 1;public static int SIZE = SOUND_DI ;//音频数量//init sound poolpublic static void initSoundPool(Context context) {UtilSound.context = context;sp = new SoundPool (SIZE, AudioManager.STREAM_MUSIC, 0);suondMap = new HashMap();//tips soundssuondMap.put(SOUND_GET_SUCCESS,sp.load(context, R.raw.di, SOUND_DI));}//play soundpublic static void play(int soundID) {if(context==null||sp==null){Log.e("gcy", "play failed!"+context+" SoundPool="+sp );//return;}try {AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);float audioMaxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);float audioCurrentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);float volumnRatio = audioCurrentVolume / audioMaxVolume;//第一个参数soundID//第二个参数leftVolume为左侧音量值(范围= 0.0到1.0)//第三个参数rightVolume为右的音量值(范围= 0.0到1.0)//第四个参数priority 为流的优先级,值越大优先级高,影响当同时播放数量超出了最大支持数时SoundPool对该流的处理//第五个参数loop 为音频重复播放次数,0为值播放一次,-1为无限循环,其他值为播放loop+1次//第六个参数 rate为播放的速率,范围0.5-2.0(0.5为一半速率,1.0为正常速率,2.0为两倍速率)sp.play(soundID, volumnRatio, volumnRatio, 0, 0, 1f);//0.5-2.0 speed} catch (Exception e) {e.printStackTrace();}}}
3,初始化声音播放类,一般在onCreate中调用
UtilSound.initSoundPool (MainActivity.this);//初始化语音播放类
4,调用播放,初始化后可以多次调用
UtilSound.play(UtilSound.SOUND_DI);//播放 di
5,播放速度与音量等参数调节