soundeffects.java

来自「使用java 开发的手机小游戏」· Java 代码 · 共 90 行

JAVA
90
字号

import javax.microedition.media.*;
import java.io.*;

class SoundEffects {
	private static SoundEffects instance;

	private Player backgroundPlayer;

	private SoundEffects() {
		backgroundPlayer = createPlayer("/background.mid", "audio/midi");
	}

	static SoundEffects getInstance() {
		if (instance == null) {
			instance = new SoundEffects();
		}
		return instance;
	}

	void startBackgroundSound() {
		startBackPlayer(backgroundPlayer);
	}

	void stopBackgroundSound() {
		stopPlayer(backgroundPlayer);
	}

	void startGameOverSound() {
		startEffectSound(createPlayer("/gameover.mid", "audio/midi"));
	}
	void stopGameOverSound(){
		stopPlayer(createPlayer("/gameover.mid", "audio/midi"));
	}

	void startHighScoreSound() {
		startEffectSound(createPlayer("/highscore.mid", "audio/midi"));
	}
	void stopHighScoreSound(){
		stopPlayer(createPlayer("/highscore.mid", "audio/midi"));
	}

	private void startBackPlayer(Player p) {
		if (p != null) {
			try {
				p.stop();
				p.setLoopCount(-1);
				p.start();
			} catch (MediaException me) {
				// ignore
			}
		}
	}
	private void startEffectSound(Player p){
		if(p != null) {
			try {
				p.stop();
				p.setLoopCount(1);
				p.start();
			} catch (MediaException me) {
				// ignore
			}
		}
	}

	protected void stopPlayer(Player p) {

		if (p != null) {
			try {
				p.stop();
			} catch (MediaException me) {
				System.out.println("stop problem");
			}
		}
	}

	private Player createPlayer(String filename, String format) {
		Player p = null;
		try {
			InputStream is = getClass().getResourceAsStream(filename);
			p = Manager.createPlayer(is, format);
			p.prefetch();
		} catch (IOException ioe) {
			// ignore
		} catch (MediaException me) {
			// ignore
		}
		return p;
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?