Skip to content

Instantly share code, notes, and snippets.

@liangfu
Created July 13, 2012 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liangfu/3102314 to your computer and use it in GitHub Desktop.
Save liangfu/3102314 to your computer and use it in GitHub Desktop.
QSound interface with SDL_mixer implementation
/**
* @file QSound2.h
* @author Liangfu Chen <chenclf@gmail.com>
* @date Tue Jul 10 14:39:25 2012
*
* @brief QSound interface with SDL_mixer implementation
*
* Phonon is not the default option while compile Qt4.
* This class is designed to enable brief sound playback in
* the Linux environment.
*
* Usage:
* QSound2 m_sound("sound/music.wav");
* m_sound.play();
* if (!m_sound.isFinnished()){
* m_sound.stop();
* }
*/
#ifndef __Q_SOUND2_H__
#define __Q_SOUND2_H__
#include <QThread>
#include <SDL/SDL.h>
#include <SDL/SDL_mixer.h>
class QSound2 : public QThread
{
char m_soundfn[1024];
// Pointer to our sound, in memory
Mix_Chunk * m_sound;
// Channel on which our sound is played
int m_channel;
protected:
void run(){
// Wait until the sound has stopped playing
if (Mix_Playing(m_channel) == 0){
stop();
return;
}
exec();
}
public:
QSound2(const char * fn):
m_sound(NULL)
{
strcpy(m_soundfn, fn);
int audio_rate = 22050;// Frequency of audio playback
// Format of the audio we're playing
Uint16 audio_format = AUDIO_S16SYS;
int audio_channels = 2;//2 channels = stereo
int audio_buffers = 4096;//Size of the audio buffers in memory
// Initialize BOTH SDL video and SDL audio
if (SDL_Init(SDL_INIT_AUDIO) != 0) {
printf("Unable to initialize SDL: %s\n", SDL_GetError());
}
// Initialize SDL_mixer with our chosen audio settings
if (Mix_OpenAudio(audio_rate, audio_format,
audio_channels, audio_buffers) != 0) {
printf("Unable to initialize audio: %s\n", Mix_GetError());
}
// Load our WAV file from disk
m_sound = Mix_LoadWAV(m_soundfn);
if (m_sound == NULL) {
printf("Unable to load WAV file: %s\n", Mix_GetError());
}
}
void play(){
// Play our sound file, and capture the channel on which it is played
m_channel = Mix_PlayChannel(-1, m_sound, 0);
if (m_channel == -1) {
printf("Unable to play WAV file: %s\n", Mix_GetError());
}
start();
}
bool isPlaying() const {return isRunning();}
bool isFinnished() const {return (!isRunning());}
void stop(){
Mix_HaltChannel(-1);
quit();
}
~QSound2(){
// Release the memory allocated to our sound
Mix_FreeChunk(m_sound);
// Need to make sure that SDL_mixer and SDL have a chance to clean up
Mix_CloseAudio();
SDL_Quit();
}
};
#endif //__Q_SOUND2_H__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment