Using sound with SDL_Mixer in C++
Hi there, i am currently new to C++ and was using the lazyfoo tutorials to learn how to use the SDL library. I am trying to make a game, and i followed everything in the LazyFoo tutorials on how to get music into my game using SDL_Mixer.h but when compiling my code the window appears for a second with a black screen and then disappears lol. I was hoping someone on here could possible fix my problem or guide me in the right direction? My code in my main.cpp file is as follows:
// The headers
#include "SDL.h"
#include "SDL_image.h"
#include "SDL_ttf.h"
#include "SDL_mixer.h"
#include "timer.h"
#include "screen.h"
#include "image.h"
#include "player.h"
#include "animation.h"
#include <string>
#include <sstream>
#include <vector>
using namespace std;
// The surfaces that will be used
SDL_Surface *background = NULL;
SDL_Surface *facingR = NULL;
SDL_Surface *facingL = NULL;
SDL_Surface *defaultFace = NULL;
Mix_Music *music = NULL;
// Make the shapes
Player player_one, other;
// Function prototypes
bool init();
bool load_files();
void clean_up();
void Player::show()
{
if(player_one.velocityX >= 0 && stopWalkingRight == true) {
// Show the player
apply_surface(box.x - camera.x, box.y - camera.y, facingR, screen, 0);
}
else if(player_one.velocityX <= 0 && stopWalkingLeft == true) {
// Show the player
apply_surface(box.x - camera.x, box.y - camera.y, facingL, screen, 0);
}
else {
// Show the player
apply_surface(box.x - camera.x, box.y - camera.y, defaultFace, screen, 0);
}
}
int main(int argc, char* args[])
{
// Quit flag
bool quit = false;
// Keep track of the current frame
int frame = 0;
// Initialise
if(init() == false) {
return 1;
}
// Load the files
if(load_files() == false) {
return 1;
}
// Start the update timer
update.start();
// Start the frame timer
fps.start();
/*vector<SDL_Rect> box(1);
Circle other;*/
// Set shapes' attributes
/*box[0].x = 60;
box[0].y = 60;
box[0].w = 40;
box[0].h = 40;
other.x = 30;
other.y = 30;
other.r = PLAYER_WIDTH/2;*/
// Set the wall
wall[0].x = 300;
wall[0].y = 40;
wall[0].w = 40;
wall[0].h = 400;
// Set the sprite sheet clips
set_clips();
// Make the sprite
Ani walk;
// While the user hasn't quit
while(quit == false) {
// While there's events to handle
while(SDL_PollEvent(&event)) {
// Handle events for the player
player_one.handle_input();
// Handle events for the sprite
walk.handle_events();
// If a key was pressed
if(event.type == SDL_KEYDOWN) {
// If Space was pressed
if(event.key.keysym.sym == SDLK_SPACE) {
// If there is no music playing
if(Mix_PlayingMusic() == 0) {
// Play the music
if(Mix_PlayMusic(music, 0) == -1) {
return 1;
}
}
// If the music is being played
else {
// If the music is paused
if(Mix_PausedMusic() == 1) {
// Resume the music
Mix_ResumeMusic();
}
// If the music is playing
else {
// Pause the music
Mix_PauseMusic();
}
}
}
// If 0 was pressed
else if(event.key.keysym.sym == SDLK_0) {
// Stop the music
Mix_HaltMusic();
}
// If escape was pressed
else if(event.key.keysym.sym == SDLK_ESCAPE) {
quit = true;
}
}
// If the user has closed the window
if(event.type == SDL_QUIT) {
// Quit the program
quit = true;
}
}
/*if(player_one.getYpos() == 150) {
player_one.jumping = false;
}
if(player_one.jumping == false) {
if(player_one.getYpos() < (LEVEL_HEIGHT - PLAYER_HEIGHT)) {
while(player_one.velocityY < 5) {
player_one.velocityY += ACCEL;
player_one.jumping = false;
}
}
else {
player_one.velocityY = 0;
}
}*/
// Move the sprite
walk.move();
// Set the camera
player_one.set_camera();
// Move the dot
player_one.move();
// Apply the background
apply_surface(0, 0, background, screen, &camera);
//Show the box
/*SDL_FillRect(screen, &box[0], SDL_MapRGB(screen->format, 0x00, 0x00, 0x00));*/
//Show the wall
/*SDL_FillRect(screen, &wall[0], SDL_MapRGB(screen->format, 0x77, 0x77, 0x77));*/
// Show other player
/*apply_surface(other.getXpos() - other.getRpos(), other.getYpos() - other.getRpos(), player, screen, 0);*/
// Show the dot on the screen
player_one.show();
// Show the sprite on the screen
/*walk.show();*/
// Update the screen
if(SDL_Flip(screen) == -1) {
return 1;
}
// Increment the frame counter
frame++;
// Cap the frame rate
while(fps.get_ticks() < 1000/FRAMES_PER_SECOND) {
SDL_Delay((1000/FRAMES_PER_SECOND) - fps.get_ticks());
}
// If a second has passed since the caption was last updated
if(update.get_ticks() > 1000) {
// The frame rate as a string
stringstream caption;
// Calculate the frames per second and create the string
caption << "My Game | FPS: " << frame / (fps.get_ticks() / 1000.f) << " Velocity: " << player_one.getVelY() << " Offset X: " << player_one.getYpos();
// Reset the caption
SDL_WM_SetCaption(caption.str().c_str(), "");
// Restart the update timer
update.start();
}
}
// Free the surface and quit SDL
clean_up();
// If everything went ok
return 0;
}
bool init()
{
// Initialise all SDL subsystems
if(SDL_Init(SDL_INIT_EVERYTHING) == -1) {
return false;
}
// Set up the screen
screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE);
// If there was an error in setting up the screen
if(screen == NULL) {
return false;
}
// Initialise SDL_mixer
if(Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) == -1) {
return false;
}
// Set the window caption
SDL_WM_SetCaption("My Game", "");
// If everything initialises fine
return true;
}
bool load_files()
{
// Load the image
background = load_image("background1.jpg");
ani = load_image("walking.png");
// If there was an error in loading the image
if(background == NULL) {
return false;
}
facingL = load_image("character_facingL.gif");
facingR = load_image("character_facingR.gif");
defaultFace = facingR;
if(facingL == NULL || facingR == NULL) {
return false;
}
// Load the music
music = Mix_LoadMUS("beat.wav");
// If there was a problem loading the music
if(music == NULL) {
return false;
}
// If everything loaded successfully
return true;
}
void clean_up()
{
// Free the image
SDL_FreeSurface(background);
// Free the player
SDL_FreeSurface(facingL);
SDL_FreeSurface(facingR);
SDL_FreeSurface(ani);
// Free the sound effects
Mix_CloseAudio();
// Quit SDL
SDL_Quit();
}
Thanks!
Firstly, when you're posting code (on almost any forum) use the
As far as pointing you in the right direction:
Debugging is an essential skill for any programmer to have, even if you're only planning on making programming a hobby.
Presumably you're using an IDE (Integrated Development Environment), something like Visual Studio or DevC++ or CodeBlocks.
All of these have a 'debug' mode, which allows you step through your code one line at a time.
This enables you to see what lines of code are working and what lines are not.
If you're feeling lazy you can also just launch debug mode, put a breakpoint at the beginning of your program, then run it from there and wait for the crash - debug mode will usually log the callstack of your app so you can see what was happening just before the crash and that will give you an idea.
Aside from using debug mode, another useful tool when debugging is using COUT and/or CERR to output something whenever an error occurs.
CERR is used for errors, COUT is a general purpose type thing.
in your code you've got statements like:
so that's saying "If Mix_Audio was unable to open the audio output device, close the program"
to make this easier to debug, every time you return a value which will cause your application to close, do something like this:
because you're using SDL this will result in a text file being created called cerr.txt, and inside that you'll find the line "Unable to open audio device. Mix_GetError: qwerty".
To achieve the same thing in debug mod you'd set a breakpoint on every "return false;" statement you have in your init code (and anywhere else you do it that would cause the program to exit) and then run the program in debug mode.
Whenever one of those lines is executed the program will stop and you'll be able to see what's failing.
A good reason for using CERR/COUT is because presumably you're going to be building this as an exe one day, so when you distribute it to whoever and it crashes, you'll be able to get them to send you the error log to see what's going on.
tags i.e.:SDL_Surface *background = NULL;
As far as pointing you in the right direction:
Debugging is an essential skill for any programmer to have, even if you're only planning on making programming a hobby.
Presumably you're using an IDE (Integrated Development Environment), something like Visual Studio or DevC++ or CodeBlocks.
All of these have a 'debug' mode, which allows you step through your code one line at a time.
This enables you to see what lines of code are working and what lines are not.
If you're feeling lazy you can also just launch debug mode, put a breakpoint at the beginning of your program, then run it from there and wait for the crash - debug mode will usually log the callstack of your app so you can see what was happening just before the crash and that will give you an idea.
Aside from using debug mode, another useful tool when debugging is using COUT and/or CERR to output something whenever an error occurs.
CERR is used for errors, COUT is a general purpose type thing.
in your code you've got statements like:
if(Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) == -1) {return false;}
so that's saying "If Mix_Audio was unable to open the audio output device, close the program"
to make this easier to debug, every time you return a value which will cause your application to close, do something like this:
if(Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) == -1){cerr << "Unable to open audio device. Mix_GetError: " << Mix_GetError() << endl;return false;}
because you're using SDL this will result in a text file being created called cerr.txt, and inside that you'll find the line "Unable to open audio device. Mix_GetError: qwerty".
To achieve the same thing in debug mod you'd set a breakpoint on every "return false;" statement you have in your init code (and anywhere else you do it that would cause the program to exit) and then run the program in debug mode.
Whenever one of those lines is executed the program will stop and you'll be able to see what's failing.
A good reason for using CERR/COUT is because presumably you're going to be building this as an exe one day, so when you distribute it to whoever and it crashes, you'll be able to get them to send you the error log to see what's going on.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement