wavloader.cpp

来自「一個遊戲教程」· C++ 代码 · 共 139 行

CPP
139
字号
// WAVLoader.cpp: implementation of the CWAVLoader class.
//
//////////////////////////////////////////////////////////////////////

#include "WAVLoader.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CWAVLoader::CWAVLoader()
{
	//initialize members
	lpWfx=NULL;
	dwDataLength=0;
	ucData=NULL;
}

CWAVLoader::~CWAVLoader()
{
	//destroy any data we may have
	Destroy();
}

//get data length
DWORD CWAVLoader::GetLength()
{
	return(dwDataLength);
}

//get data pointer
UCHAR* CWAVLoader::GetData()
{
	return(ucData);
}

//get pointer to format
LPWAVEFORMATEX CWAVLoader::GetFormat()
{
	return(lpWfx);
}

//load from a file
void CWAVLoader::Load(LPCTSTR lpszFilename)
{
	//destroy any old buffer
	Destroy();

	//four character buffer
	char Buffer[5];
	Buffer[4]=0;

	//read length
	DWORD dwNumRead;

	//length variable
	DWORD dwLength;

	//data buffer
	UCHAR* ucTemp;

	//open a handle to the file
	HANDLE hfile=CreateFile(lpszFilename,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);

	ReadFile(hfile,Buffer,4,&dwNumRead,NULL);//"RIFF"

	ReadFile(hfile,&dwLength,sizeof(dwLength),&dwNumRead,NULL);//length of file

	ReadFile(hfile,Buffer,4,&dwNumRead,NULL);//"WAVE"

	//chunks
	bool done=false;

	while(!done)
	{
		ReadFile(hfile,Buffer,4,&dwNumRead,NULL);//chunk header

		ReadFile(hfile,&dwLength,sizeof(dwLength),&dwNumRead,NULL);//length of chunk

		ucTemp=new UCHAR[dwLength];

		ReadFile(hfile,ucTemp,dwLength,&dwNumRead,NULL);

		//dependin on the chunk header, do something

		if(strcmp("fmt ",Buffer)==0)
		{
			//format chunk

			//allocate format
			lpWfx=new WAVEFORMATEX;

			//clear out format
			memset(lpWfx,0,sizeof(WAVEFORMATEX));
	
			//copy from buffer
			memcpy(lpWfx,ucTemp,dwLength);
		}

		if(strcmp("data",Buffer)==0)
		{
			//data chunk

			//allocate data buffer
			ucData=new UCHAR[dwLength];

			//copy length
			dwDataLength=dwLength;
			
			//copy buffer
			memcpy(ucData,ucTemp,dwDataLength);

			//we are done, and need no more chunks
			done=true;
		}

		delete ucTemp;
	}
	//close the file
	CloseHandle(hfile);
}

//destroy buffer
void CWAVLoader::Destroy()
{
	//if we have data, delete
	if(ucData)
	{
		//delete format and data buffers
		delete lpWfx;
		delete ucData;

		//reinitialize
		lpWfx=NULL;
		ucData=NULL;
		dwDataLength=NULL;
	}
}

⌨️ 快捷键说明

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