SDL游戏之路(二十一)--声音



声音

游戏中的音乐有两种1.背景音乐,2.音效。

定义一个声音类来管理:

#ifndef SKMUSIC_H_
#define SKMUSIC_H_

#include "SkComm.h"
namespace sk_park {

/**1:效果音乐 2:背景音乐**/
typedef enum _SkMusicType {
	SK_MUSIC_TYPE_CHUNK = 1, SK_MUSIC_TYPE_MUSIC = 2,
} SkMusicType;

class SkMusic {
public:
	SkMusic();
	virtual ~SkMusic();
	/**加载音乐文件**/
	int load(SkMusicType mType, const char * pPath);
	void start();
	void stop();
	void pause();
private:
	SkMusicType m_mType;
	static Sint32 m_iMusicNum;
	Mix_Music* m_pMusic;
	Mix_Chunk* m_pChunk;
};

}

extern sk_park::SkMusic g_SkMusic;

#endif /* SKMUSIC_H_ */


实现如下:

#include "pch.h"

#include "SkMusic.h"
#include "SkFile.h"
#include "SkString.h"
using namespace sk_park;

Sint32 SkMusic::m_iMusicNum = 0;
SkMusic::SkMusic() {
	if (m_iMusicNum == 0) {
		int iRet = Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096);
		if (iRet == -1) {
			g_SkComm.log("[%s][%d]Mix_OpenAudio err = %d", __FILE__, __LINE__,
					iRet);
			g_SkComm.myexit();
		}
	}
	m_iMusicNum++;
	m_pMusic = NULL;
	m_pChunk = NULL;

}
SkMusic::~SkMusic() {
	if (m_pChunk != NULL) {
		Mix_FreeChunk(m_pChunk);
		m_pChunk = NULL;
	}
	if (m_pMusic != NULL) {
		Mix_FreeMusic(m_pMusic);
		m_pMusic = NULL;
	}
	m_iMusicNum--;
	if (m_iMusicNum == 0) {
		Mix_CloseAudio();
	}
}
int SkMusic::load(SkMusicType mType, const char * pPath) {
	SkString sPath = g_SkFile.getRootPath();
	sPath.append("/").append(pPath);
	m_mType = mType;
	if (SK_MUSIC_TYPE_CHUNK == m_mType) {
		m_pChunk = Mix_LoadWAV(sPath.c_str());
		if (m_pChunk != NULL) {
			return 0;
		} else {
			return -1;
		}
	} else {
		m_pMusic = Mix_LoadMUS(sPath.c_str());
		if (m_pMusic != NULL) {
			return 0;
		} else {
			return -1;
		}
	}
	return -1;
}
void SkMusic::start() {
	if (SK_MUSIC_TYPE_CHUNK == m_mType) {
		if (m_pChunk != NULL) {
			Mix_PlayChannel(-1, m_pChunk, 0);
		}
	} else {
		if (Mix_PlayingMusic() == false) {
			if (m_pMusic != NULL) {
				Mix_PlayMusic(m_pMusic, -1);
			}
		} else {
			if (Mix_PausedMusic() == 1) {
				Mix_ResumeMusic();
			} else {
				//Mix_PauseMusic();
			}
		}

	}
}
void SkMusic::stop() {
	if (SK_MUSIC_TYPE_MUSIC == m_mType) {
		Mix_HaltMusic();
	}
}
void SkMusic::pause() {
	if (SK_MUSIC_TYPE_MUSIC == m_mType) {
		Mix_PauseMusic();
	}
}

SkMusic g_SkMusic;


你可能感兴趣的:(移动游戏)