SDL3 Desktop: SDL3_mixer Setup (MinGW 13.1) SDL3 для Desktop: Настройка SDL3_mixer (MinGW 13.1)
A guide to configuring the SDL3_mixer extension library with CMake and MinGW. Руководство по настройке библиотеки расширения SDL3_mixer с использованием CMake и MinGW.
1. Obtain SDL3_mixer 3.2.2 1. Получение SDL3_mixer 3.2.2
-
Download two archives from the official release page:
Скачайте два архива со страницы официального релиза:
-
Extract the SDL3_mixer-devel-3.2.2-mingw.zip archive to the
C:/libs/SDL3_mixer-devel-3.2.2-mingwfolder. Распакуйте архив SDL3_mixer-devel-3.2.2-mingw.zip в папкуC:/libs/SDL3_mixer-devel-3.2.2-mingw. -
Move the headers and libraries so the structure is
SDL3_mixer-devel-3.2.2-mingw/include, etc: Переместите заголовочные файлы и библиотеки так, чтобы структура папок былаSDL3_mixer-devel-3.2.2-mingw/includeи т. д.:
-
Extract the SDL3_mixer-3.2.2-win32-x64.zip archive so the path is exactly
C:/libs/SDL3_mixer-3.2.2-win32-x64: Распакуйте архив SDL3_mixer-3.2.2-win32-x64.zip так, чтобы путь был именноC:/libs/SDL3_mixer-3.2.2-win32-x64:
2. Add SDL3_mixer to Environment Variables (Path) 2. Добавление SDL3_mixer в переменные среды (Path)
C:\libs\SDL3_mixer-3.2.2-win32-x64
3. Project Structure and Assets 3. Структура проекта и ресурсы
Before creating the files, download the required asset: Перед созданием файлов скачайте необходимый ресурс:
- Download the WAV file: Picked Coin Echo 2.zip Скачайте WAV-файл: Picked Coin Echo 2.zip
- Note: This is a free file taken from this link. Примечание. Это бесплатный файл, который был взят по ссылке.
C Project: Create an empty folder named mixer-sdl3-c and set up the following hierarchy by creating new CMakeLists.txt and main.c files:
Проект на C: Создайте пустую папку с именем mixer-sdl3-c и подготовьте следующую иерархию, создав файлы CMakeLists.txt и main.c:
mixer-sdl3-c/
├── CMakeLists.txt
├── assets/audio/
│ └── Picked Coin Echo 2.wav
└── src/
└── main.c
C++ Project: Create an empty folder named mixer-sdl3-cpp and set up the following hierarchy by creating new CMakeLists.txt and main.cpp files:
Проект на C++: Создайте пустую папку с именем mixer-sdl3-cpp и подготовьте следующую иерархию, создав файлы CMakeLists.txt и main.cpp:
mixer-sdl3-cpp/
├── CMakeLists.txt
├── assets/audio/
│ └── Picked Coin Echo 2.wav
└── src/
└── main.cpp
4. CMake Configuration 4. Конфигурация CMake
C Project: Copy and paste the following code into the CMakeLists.txt file:
Проект на C: Скопируйте и вставьте следующее содержимое в файл CMakeLists.txt:
set(CMAKE_BUILD_TYPE "Debug")
cmake_minimum_required(VERSION 3.21)
project(mixer-sdl3-c)
set(SDL3_DIR "C:/libs/SDL3-devel-3.4.8-mingw/lib/cmake/SDL3")
set(SDL3_mixer_DIR "C:/libs/SDL3_mixer-devel-3.2.2-mingw/lib/cmake/SDL3_mixer")
find_package(SDL3 REQUIRED)
find_package(SDL3_mixer REQUIRED)
add_executable(app)
target_sources(app PRIVATE src/main.c)
# Copy the assets folder to the dist folder
if(EXISTS "${CMAKE_SOURCE_DIR}/assets")
add_custom_command(TARGET app POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
"${CMAKE_SOURCE_DIR}/assets"
"$<TARGET_FILE_DIR:app>/assets"
COMMENT "Copying assets directory"
)
endif()
target_link_libraries(app PRIVATE SDL3_mixer::SDL3_mixer SDL3::SDL3)
target_link_options(app PRIVATE -mconsole)
C++ Project: Copy and paste the following code into the CMakeLists.txt file:
Проект на C++: Скопируйте и вставьте следующее содержимое в файл CMakeLists.txt:
set(CMAKE_BUILD_TYPE "Debug")
cmake_minimum_required(VERSION 3.21)
project(mixer-sdl3-cpp)
set(SDL3_DIR "C:/libs/SDL3-devel-3.4.8-mingw/lib/cmake/SDL3")
set(SDL3_mixer_DIR "C:/libs/SDL3_mixer-devel-3.2.2-mingw/lib/cmake/SDL3_mixer")
find_package(SDL3 REQUIRED)
find_package(SDL3_mixer REQUIRED)
add_executable(app)
target_sources(app PRIVATE src/main.cpp)
# Copy the assets folder to the dist folder
if(EXISTS "${CMAKE_SOURCE_DIR}/assets")
add_custom_command(TARGET app POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
"${CMAKE_SOURCE_DIR}/assets"
"$<TARGET_FILE_DIR:app>/assets"
COMMENT "Copying assets directory"
)
endif()
target_link_libraries(app PRIVATE SDL3_mixer::SDL3_mixer SDL3::SDL3)
target_link_options(app PRIVATE -mconsole)
5. Source Code (Audio Playback) 5. Исходный код (Воспроизведение аудио)
Copy and paste the following code into the src/main.c (or src/main.cpp) file:
Скопируйте и вставьте следующее содержимое в файл src/main.c (или src/main.cpp):
main.c / main.cpp
#define SDL_MAIN_USE_CALLBACKS 1
#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>
#include <SDL3_mixer/SDL_mixer.h>
static SDL_Window *window = NULL;
static MIX_Mixer *mixer = NULL;
static MIX_Audio *audio = NULL;
static MIX_Track *track = NULL;
SDL_AppResult SDL_AppInit(void **appstate, int argc, char *argv[]) {
// Initialize SDL
if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO)) {
return SDL_APP_FAILURE;
}
// Initialize Mixer 3 and create a Mixer Device
if (!MIX_Init()) {
return SDL_APP_FAILURE;
}
// This replaces Mix_OpenAudio
mixer = MIX_CreateMixerDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, NULL);
if (!mixer) {
SDL_Log("Mixer creation failed: %s", SDL_GetError());
return SDL_APP_FAILURE;
}
window = SDL_CreateWindow("SDL3 Mixer", 400, 300, 0);
// Load Audio (replaces Mix_LoadMUS)
// The 'true' parameter tells Mixer to cache the data in memory
audio = MIX_LoadAudio(mixer, "assets/audio/Picked Coin Echo 2.wav", true);
if (!audio) {
SDL_Log("Load failed: %s", SDL_GetError());
return SDL_APP_FAILURE;
}
// Create a Track to play the audio
track = MIX_CreateTrack(mixer);
if (!track) {
return SDL_APP_FAILURE;
}
// Bind the audio to the track and play it
MIX_SetTrackAudio(track, audio);
// Play once (0 loops). For infinite loop, use MIX_SetTrackLooping(track, true)
MIX_PlayTrack(track, 0);
return SDL_APP_CONTINUE;
}
SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event) {
if (event->type == SDL_EVENT_QUIT) {
return SDL_APP_SUCCESS;
}
return SDL_APP_CONTINUE;
}
SDL_AppResult SDL_AppIterate(void *appstate) {
return SDL_APP_CONTINUE;
}
void SDL_AppQuit(void *appstate, SDL_AppResult result) {
/*
In SDL_mixer 3, MIX_Quit() is powerful: it automatically cleans up
all mixers, tracks, and audio objects associated with the library.
*/
MIX_Quit();
}
6. Opening the Project in IDEs 6. Открытие проекта в IDE
Open the CMakeLists.txt file in CLion or Qt Creator. CMake will handle the rest. Откройте файл CMakeLists.txt в CLion или Qt Creator. CMake позаботится об остальном.
7. Automation Scripts (.bat) 7. Скрипты автоматизации (.bat)
You can open the project folder in Sublime Text 4 (or Notepad++). Create the following .bat scripts in the project root directory to automate the configuration, building, and running of your application:
Вы можете открыть папку проекта в Sublime Text 4 (или Notepad++). Создайте следующие .bat скрипты в корневой директории проекта для автоматизации конфигурации, сборки и запуска вашего приложения:
1. config-exe.bat
cmake -G "MinGW Makefiles" -S . -B dist/exe
2. build-exe.bat
cd dist\exe
cmake --build .
cd ..\..
3. run-exe.bat
dist\exe\app
To build and launch the application, run these scripts in the terminal in the following order:
Чтобы собрать и запустить приложение, выполните эти скрипты в терминале в следующем порядке:
config-exe
build-exe
run-exe
Support My Work Поддержать проект
If these tutorials helped you, consider buying me a coffee! Если эти туториалы вам помогли, вы можете поддержать автора.
Sberbank
Direct transfer via phone number Перевод по номеру телефона
Bybit (USDT TRC20)
Support via Cryptocurrency Поддержка криптовалютой