• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Steve Gee

No sound from OpenAL using mac.

1 post in this topic

Hi all,


I'm trying to play a simple sound for a game that I'm currently working on.  I don't want to use SDL if I can help it and came across OpenAL.  I found an example and tutorial for creating and playing sound without the alut header but I'm still having issues.  The log output is fine, it's reading the file, knows the size and so on but nothing is played.  I thought that maybe it was my game loop that was affecting it so created a new project with just the sound code to test and same result.  any help is hugely appreciated.  Thanks.



#include <cstdlib>
#include <iostream>
#include <OPENAL/al.h>
#include <OPENAL/alc.h>
using namespace std;

typedef uint32_t DWORD;
int endWithError(char* msg, int error=0)

    //Display error message in console
    cout << msg << "\n";
    return error;


int main(int argc, char *argv[])


    //Loading of the WAVE file

    FILE *fp = NULL;                                                            //Create FILE pointer for the WAVE file

    fp=fopen("Sounds/mushroom_jump.wav","rb");                                            //Open the WAVE file

    if (!fp) return endWithError("Failed to open file");                        //Could not open file
    //Variables to store info about the WAVE file (all of them is not needed for OpenAL)

    char type[4];

    DWORD size,chunkSize;

    short formatType,channels;

    DWORD sampleRate,avgBytesPerSec;

    short bytesPerSample,bitsPerSample;

    DWORD dataSize;

    //Check that the WAVE file is OK

    fread(type,sizeof(char),4,fp);                                              //Reads the first bytes in the file

    if(type[0]!='R' || type[1]!='I' || type[2]!='F' || type[3]!='F')            //Should be "RIFF"

        return endWithError ("No RIFF");                                            //Not RIFF

    fread(&size, sizeof(DWORD),1,fp);                                           //Continue to read the file

    fread(type, sizeof(char),4,fp);                                             //Continue to read the file

    if (type[0]!='W' || type[1]!='A' || type[2]!='V' || type[3]!='E')           //This part should be "WAVE"

        return endWithError("not WAVE");                                            //Not WAVE

    fread(type,sizeof(char),4,fp);                                              //Continue to read the file

    if (type[0]!='f' || type[1]!='m' || type[2]!='t' || type[3]!=' ')           //This part should be "fmt "

        return endWithError("not fmt ");                                            //Not fmt

    //Now we know that the file is a acceptable WAVE file

    //Info about the WAVE data is now read and stored


    if (type[0]!='d' || type[1]!='a' || type[2]!='t' || type[3]!='a')           //This part should be "data"
        return endWithError("Missing DATA");                                        //not data

    fread(&dataSize,sizeof(DWORD),1,fp);                                        //The size of the sound data is read

    //Display the info about the WAVE file

    cout << "Chunk Size: " << chunkSize << "\n";
    cout << "Format Type: " << formatType << "\n";
    cout << "Channels: " << channels << "\n";
    cout << "Sample Rate: " << sampleRate << "\n";
    cout << "Average Bytes Per Second: " << avgBytesPerSec << "\n";
    cout << "Bytes Per Sample: " << bytesPerSample << "\n";
    cout << "Bits Per Sample: " << bitsPerSample << "\n";
    cout << "Data Size: " << dataSize << "\n";

    unsigned char* buf= new unsigned char[dataSize];                            //Allocate memory for the sound data

    //cout << fread(buf,sizeof(BYTE),dataSize,fp) << " bytes loaded\n";           //Read the sound data and display the

                                                                                //number of bytes loaded.

                                                                                //Should be the same as the Data Size if OK

    //Now OpenAL needs to be initialized
    ALCdevice *device;                                                          //Create an OpenAL Device
    ALCcontext *context;                                                        //And an OpenAL Context
    device = alcOpenDevice(NULL);                                               //Open the device
    if(!device) return endWithError("no sound device");                         //Error during device oening
    context = alcCreateContext(device, NULL);                                   //Give the device a context
    alcMakeContextCurrent(context);                                             //Make the context the current
    if(!context) return endWithError("no sound context");                       //Error during context handeling
    ALuint source;                                                              //Is the name of source (where the sound come from)

    ALuint buffer;                                                           //Stores the sound data

    ALuint frequency=sampleRate;;                                               //The Sample Rate of the WAVE file

    ALenum format=0;                                                            //The audio format (bits per sample, number of channels)
    alGenBuffers(1, &buffer);                                                    //Generate one OpenAL Buffer and link to "buffer"
    alGenSources(1, &source);                                                   //Generate one OpenAL Source and link to "source"
    if(alGetError() != AL_NO_ERROR) return endWithError("Error GenSource");     //Error during buffer/source generation

    //Figure out the format of the WAVE file

    if(bitsPerSample == 8)
        if(channels == 1)
            format = AL_FORMAT_MONO8;
        else if(channels == 2)
            format = AL_FORMAT_STEREO8;
    else if(bitsPerSample == 16)
        if(channels == 1)
            format = AL_FORMAT_MONO16;
        else if(channels == 2)
            format = AL_FORMAT_STEREO16;
    if(!format) return endWithError("Wrong BitPerSample");                      //Not valid forma
    alBufferData(buffer, format, buf, dataSize, frequency);                    //Store the sound data in the OpenAL Buffer
    if(alGetError() != AL_NO_ERROR)
        return endWithError("Error loading ALBuffer");                              //Error during buffer loading


    //Sound setting variables

    ALfloat SourcePos[] = { 0.0, 0.0, 0.0 };                                    //Position of the source sound
    ALfloat SourceVel[] = { 0.0, 0.0, 0.0 };                                    //Velocity of the source sound
    ALfloat ListenerPos[] = { 0.0, 0.0, 0.0 };                                  //Position of the listener
    ALfloat ListenerVel[] = { 0.0, 0.0, 0.0 };                                  //Velocity of the listener
    ALfloat ListenerOri[] = { 0.0, 0.0, -1.0,  0.0, 1.0, 0.0 };                 //Orientation of the listener                                                                              //First direction vector, then vector pointing up)                                                                               //Listener
    alListenerfv(AL_POSITION,    ListenerPos);                                  //Set position of the listener
    alListenerfv(AL_VELOCITY,    ListenerVel);                                  //Set velocity of the listener
    alListenerfv(AL_ORIENTATION, ListenerOri);                                  //Set orientation of the listener
    alSourcei (source, AL_BUFFER,   buffer);                                 //Link the buffer to the source
    alSourcef (source, AL_PITCH,    1.0f     );                                 //Set the pitch of the source
    alSourcef (source, AL_GAIN,     1.0f     );                                 //Set the gain of the source
    alSourcefv(source, AL_POSITION, SourcePos);                                 //Set the position of the source
    alSourcefv(source, AL_VELOCITY, SourceVel);                                 //Set the velocity of the source
    alSourcei (source, AL_LOOPING,  AL_FALSE );                                 //Set if source is looping sound

    alSourcePlay(source);                                                       //Play the sound buffer linked to the source
    if(alGetError() != AL_NO_ERROR) return endWithError("Error playing sound"); //Error when playing sound
//    system("PAUSE"); 
    std::cout << "Press any key to continue ..."; getchar();//Pause to let the sound play

    fclose(fp);                                                                 //Close the WAVE file
    delete[] buf;                                                               //Delete the sound data buffer
    alDeleteSources(1, &source);                                                //Delete the OpenAL Source
    alDeleteBuffers(1, &buffer);                                                 //Delete the OpenAL Buffer
    alcMakeContextCurrent(NULL);                                                //Make no context current
    alcDestroyContext(context);                                                 //Destroy the OpenAL Context
    alcCloseDevice(device);                                                     //Close the OpenAL Device   

    return EXIT_SUCCESS;                                                        



Edited by muffinmannen

Share this post

Link to post
Share on other sites

I've just assigned the above to a key press in my original game.  I had some crackles and then the sound actually worked - whoop, but only when it's paused.  Could someone possibly explain or elaborate on how this should be implemented properly please?  


Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  
Followers 0