一、采用SoundPool来播放音频
private SoundPool soundPool;
private HashMap<Integer, Integer> soundMap = new HashMap<Integer, Integer>();
soundPool = new SoundPool(100, AudioManager.STREAM_SYSTEM, 5);
//加载音频资源
private void loadAudioResource() {
Log.e(TAG, " loadAudioResource() ");
if (soundMap.size() > 0) {
soundMap.clear();
}
soundMap.put(0, soundPool.load(this, R.raw.start1, 1));
soundMap.put(1, soundPool.load(this, R.raw.stop, 1));
}
//播放音频资源
public void playSound(int type) {
Log.e(TAG,
" playSound() type = " + type + " soundMap = "
+ soundMap.size());
if (type == 1) {
soundPool.play(soundMap.get(0), 1, 1, 2, 0, 1);
} else if (type == 2) {
soundPool.play(soundMap.get(1), 1, 1, 2, 0, 1);
}
}
二、使用MediaPlayer来播放Raw文件下面的音频
private MediaPlayer mPlayer;
private AssetFileDescriptor file;
public void playFromRawFile(Context mContext, int type) {
// 1.获取模式
AudioManager am = (AudioManager) mContext
.getSystemService(Context.AUDIO_SERVICE);
final int ringerMode = am.getRingerMode();
// 2.普通模式可以呼叫普通模式: AudioManager.RINGER_MODE_NORMAL
// 静音模式:AudioManager.RINGER_MODE_VIBRATE
// 震动模式:AudioManager.RINGER_MODE_SILENT
if (ringerMode == AudioManager.RINGER_MODE_NORMAL) {
try {
mPlayer = new MediaPlayer();
if (type == 1) {
file = mContext.getResources().openRawResourceFd(
R.raw.start);
} else if (type == 2) {
file = mContext.getResources()
.openRawResourceFd(R.raw.stop);
}
try {
mPlayer.setDataSource(file.getFileDescriptor(),
file.getStartOffset(), file.getLength());
file.close();
if (!mPlayer.isPlaying()) {
mPlayer.prepare();
mPlayer.start();
// mPlayer.setLooping(true);//循环播放
}
} catch (IOException e) {
mPlayer = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 结束播放释放资源
*/
private void stopPlayFromRawFile() {
if (mPlayer != null && mPlayer.isPlaying()) {
mPlayer.stop();
mPlayer.release();
}
mPlayer = null;
}