13. September 2017

SDL2_mixer for Android playing WAV file

In previous articles, we were talking about PNG and JPEG support in SDL2 for Android. Let’s add some sounds to our application.

The initial steps are same as in case of SDL2_image.

Register library in settings.gradle:

include ':SDL2_mixer'

The library should be stored in SDL2_mixer directory with build.gradle that written in style for a library.

Now update our C application.

First of all, it is necessary to initialize the library. Then it is possible to load the sound file.

    if (Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) == -1 ) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
                     "Couldn't open mixer: %s", SDL_GetError());
        return 2;
    }
    Mix_Chunk *sample = Mix_LoadWAV("cuckoo.wav");
    if (sample == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, 
                     "Unable to load wave file\n");
        return 3;
    }

The file WAV should be stored in app/src/main/assets. Just small reminder: this is just a virtual directory, and you won’t be able to access it from other application on Android.

Playing the sound is simple:

Mix_PlayChannel(-1, sample, 0);

The last important thing about SDL2_mixer is that you should close SDL2_mixer when exiting the main. Otherwise, when you relaunch SDLActivity, it won’t be able to play any sound.

Mix_CloseAudio();

You can find the source code at GitHub in sdl2-android-example repository. Further articles about SDL2 and android are available under the tag SDL2.

15. October 2011

Composing and playing music with HTML5

I was searching for a web based music note editor. I found HTML5 Cloud Composer from Greg Jopa.

Then I found something more like good old FastTracker: Sonant Live composer.

You can use Sonant Live composer to create tracks with music.

What is even more interesting about this composer is that you can store your song into pure JavaScript file and replay it with js-sonant.

The princeple of js-sonant is quite simple. You just store music structure into song variable and then you call createAudio. It will produce HTML5 audio object with wav rendered from your song tracks.

Here is sample code:

var songGen = new sonant();

for (var t = 0; t < 8; t++)
{
    songGen.generate(t);
}

audio = songGen.createAudio();
audio.loop = true;
audio.play();

Here you can play my simple attempt to make music. 🙂

Note: Your browser must support HTML5 audio in order to play this music. Browsers which have support for HTML5 audio: Google Chrome, Firefox, Opera, Safari.

Note 2: Please wait few seconds after you clicked the Play button. You browser will render JavaScript music notation into playable Wav.