本文旨在实践Android中播放声音的两种常见方法;
项目地址:https://github.com/avnewu/sounddemo
一.
播放短暂的声音如爆炸声警告音等;
使用SoundPool类,声音文件调入内存中,播放响应快,但是占用内存;
AudioManager manager = (AudioManager) getSystemService(AUDIO_SERVICE); float maxvolume = manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); float currentVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC); final float volume = currentVolume / maxvolume; sound1Btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { soundPool.play(soundid, volume, volume, 1, 0, 1); } });
二.
播放时间较长的背景音乐,文件存储在SD卡上;
使用MediaPlayer类,比前者麻烦一点,遵循生命周期,
1.实例化MediaPlayer;
2.设置音频资源;
3.为播放音频做准备;
4.播放;
try { mediaPlayer.setDataSource("/sdcard/dl.mid"); } catch (Exception e) { e.printStackTrace(); } try { mediaPlayer.prepare(); } catch (Exception e) { e.printStackTrace(); } if (isPlaying) { mediaPlayer.pause(); sound2Btn.setText("Play a music on SDcard"); isPlaying = false; } else { mediaPlayer.start(); mediaPlayer.setLooping(true); sound2Btn.setText("Click again to pause "); isPlaying = true; }