C++ SDL_mixer播放声音
配置请参照前面的笔记https://www.cnblogs.com/zzr-stdio/p/14514043.html
参照视频教程:https://www.bilibili.com/video/BV1Ss411e7nL/?spm_id_from=333.788.videocard.19
需要下载配置SDL,下载地址:http://www.libsdl.org/projects/SDL_mixer/,配置过程与SDL_image类似。
示例程序:
#include <iostream>
#include<SDL.h>
#include<SDL_image.h>
#include<SDL_mixer.h>
#include<vector>
using namespace std;
const int WIDTH = 800;
const int HEIGHT = 600;
int main(int argc, char* argv[])
{
::SDL_Init(SDL_INIT_VIDEO);//初始化SDL
::SDL_Window* window = ::SDL_CreateWindow("SDL test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
WIDTH, HEIGHT, SDL_WINDOW_SHOWN);//创建窗体
bool quit = false;
::SDL_Event event;
Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048);//设置声音
::Mix_Music* sound = Mix_LoadMUS("1.mp3");//加载声音文件
::Mix_Music* sound2 = Mix_LoadMUS("2.mp3");
Mix_PlayMusic(sound, 0);
while (quit == false)
{
while (::SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
quit = true;
}
else if (event.type == SDL_MOUSEBUTTONDOWN)
{
if (event.button.button == SDL_BUTTON_LEFT)
{
Mix_PlayMusic(sound, 0);
}
else if (event.button.button == SDL_BUTTON_RIGHT)
{
Mix_PlayMusic(sound2, 0);
}
}
else if (event.type == SDL_KEYDOWN)
{
switch (event.key.keysym.sym)
{
case SDLK_UP:
Mix_VolumeMusic(100);//设置音量
break;
case SDLK_DOWN:
Mix_VolumeMusic(10);
break;
case SDLK_LEFT:
break;
}
}
}
::SDL_UpdateWindowSurface(window);
}
::SDL_DestroyWindow(window);//销毁窗体
Mix_CloseAudio();
::SDL_Quit();//退出SDL
return 0;
}