Android 播放音效工具类
在Android开发中,经常会遇到需要播放音效的需求,比如在游戏中触发特定事件时播放音效。为了方便统一管理音效的播放,我们可以封装一个音效播放工具类来实现。
音效播放工具类设计
我们可以设计一个名为SoundUtil
的音效播放工具类,该类包含以下功能:
- 初始化音效资源
- 播放指定音效
- 停止播放音效
- 释放音效资源
下面是SoundUtil
类的基本结构:
public class SoundUtil {
private Context mContext;
private SoundPool mSoundPool;
private Map<Integer, Integer> mSoundMap;
public SoundUtil(Context context) {
mContext = context;
mSoundPool = new SoundPool.Builder().setMaxStreams(10).build();
mSoundMap = new HashMap<>();
}
public void loadSound(int soundId, int resId) {
int sound = mSoundPool.load(mContext, resId, 1);
mSoundMap.put(soundId, sound);
}
public void playSound(int soundId) {
int sound = mSoundMap.get(soundId);
mSoundPool.play(sound, 1, 1, 0, 0, 1);
}
public void stopSound(int soundId) {
int sound = mSoundMap.get(soundId);
mSoundPool.stop(sound);
}
public void release() {
mSoundPool.release();
mSoundPool = null;
mSoundMap.clear();
}
}
使用SoundUtil
播放音效
在使用SoundUtil
播放音效时,首先需要在Activity
或Fragment
中进行初始化,加载音效资源,并在需要的地方播放音效。示例代码如下:
public class MainActivity extends AppCompatActivity {
private SoundUtil mSoundUtil;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSoundUtil = new SoundUtil(this);
mSoundUtil.loadSound(1, R.raw.sound_effect);
Button playButton = findViewById(R.id.play_button);
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mSoundUtil.playSound(1);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
mSoundUtil.release();
}
}
关系图
下面是SoundUtil
类的关系图:
erDiagram
Context ||--|| SoundUtil : 初始化
SoundUtil ||--|> SoundPool : 使用
通过上述设计和示例代码,我们可以方便地使用SoundUtil
类来管理和播放音效,提高了代码的复用性和可维护性。在实际开发中,可以根据具体需求对SoundUtil
类进行扩展,添加更多功能,以适应不同的场景需求。