1. 程式人生 > >使用SDL播放聲音

使用SDL播放聲音

原生的SDL的介面實在是太難用了,我們可以藉助SDL提供的其他工具SDL_mixer.地址 http://www.libsdl.org/projects/SDL_mixer/

#include "SDL_image.h"
#include "SDL_mixer.h"
int main(int argc, char* argv[])
{
	SDL_Init(SDL_INIT_EVERYTHING);
	SDL_Window* window = SDL_CreateWindow("hello SDL", 100, 100, 600, 800, SDL_WINDOW_SHOWN);
	SDL_Renderer* render = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
	SDL_Event event;
	//載入聲音檔案,44100聲音一般取樣率,2雙聲道,2048把每段分成2048個位元組
	Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048);
	Mix_Music *sound = Mix_LoadMUS("C:/Users/xxxx/Desktop/2.wav");
	if (nullptr == sound)
	{
		printf("聲音失敗,%s", Mix_GetError());
	}
	Mix_PlayMusic(sound, 1);

	bool quit = false;
	while (false == quit)
	{
		while (SDL_PollEvent(&event))
		{
			if (SDL_QUIT == event.type)
			{
				quit = true;
			}
		}

		//SDL_RenderPresent(render);
		//SDL_Delay(40);
	}
	//Mix_VolumeMusic(audio_volume); //設定音量
	Mix_FreeMusic(sound); //關閉開啟音訊檔案
	Mix_CloseAudio();
    return 0;
}