⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sound.h

📁 小游戏 有碰撞检测和音乐 使用键盘openal
💻 H
字号:
#include <iostream>
#include "al/al.h"
#include "al/alc.h"
#include "al/alut.h"
#include "vorbis/vorbisfile.h"

#define BUFFER_SIZE (4096 * 10)
string intro_music_file;
string collide_sound_file;
unsigned int sbuffer;
FILE* oggFile;
OggVorbis_File oggStream;
vorbis_info* vorbisInfo;
vorbis_comment* vorbisComment;
ALuint buffers[2];//store sound data
ALuint ssource;//play sound
ALuint msource;
ALenum format;
bool audio_init;

void EmptyMusic()
{
	int queued;
	alGetSourcei(msource, AL_BUFFERS_QUEUED, &queued);
	while(queued--)
	{
		ALuint buffer;
		alSourceUnqueueBuffers(msource, 1, &buffer);
	}
}
void ReleaseMusic()
{
	alSourceStop(msource);
	EmptyMusic();
	alDeleteSources(1, &msource);
	msource = 0;
	alDeleteBuffers(1, buffers);
	ov_clear(&oggStream);
}

bool Playing() 
{
	ALenum state;
	alGetSourcei(msource, AL_SOURCE_STATE, &state);
	return (state == AL_PLAYING);
}
bool Stream(ALuint buffer) 
{
	char pcm[BUFFER_SIZE]; // pulse code modulation
	int size = 0;
	int section;
	int result;
	while(size < BUFFER_SIZE)
	{
		// file struct, buffer, length, byte packing, sample size, signed/unsigned, bitstream
		result = ov_read(&oggStream, pcm + size, BUFFER_SIZE - size, 0, 2, 1, &section);
		if(result > 0)
		size += result;
		else
		if(result < 0)
		cout << "Error : Streaming" << endl;
		else
		break;
	}
	if(size == 0) return false;
	// buffer, mono/stereo, data pointer, data size,frequency
	alBufferData(buffer, format, pcm, size, vorbisInfo->rate);
	return true;
}

bool PlayBack()
{
	if(Playing()) return true;
	if(!Stream(buffers[0])) return false;
	if(!Stream(buffers[1])) return false;
	alSourceQueueBuffers(msource, 2, buffers); // source, number of buffer, buffers
	alSourcePlay(msource);
	return true;
}
bool UpdateMusic()
{
	int processed;
	bool active = true;
	alGetSourcei(msource, AL_BUFFERS_PROCESSED, &processed);
	while(processed--)
	{
		ALuint buffer;
		alSourceUnqueueBuffers(msource, 1, &buffer);
		active = Stream(buffer);
		alSourceQueueBuffers(msource, 1, &buffer);
	}
	return active;
}

⌨️ 快捷键说明

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