Added simple SDL mixer example

This commit is contained in:
pelya
2011-02-15 09:37:26 +00:00
parent 29a7cff034
commit adc6777fe7
9 changed files with 915 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
# The application settings for Android libSDL port
AppSettingVersion=16
LibSdlVersion=1.2
AppName="SDL Simple Mixer"
AppFullName=net.olofson.simplemixer
ScreenOrientation=h
InhibitSuspend=n
AppDataDownloadUrl="Game data is 1 Mb|data.zip"
SdlVideoResize=y
SdlVideoResizeKeepAspect=n
NeedDepthBuffer=n
AppUsesMouse=y
AppNeedsTwoButtonMouse=y
AppNeedsArrowKeys=n
AppNeedsTextInput=n
AppUsesJoystick=n
AppHandlesJoystickSensitivity=n
AppUsesMultitouch=n
NonBlockingSwapBuffers=n
RedefinedKeys="SPACE"
AppTouchscreenKeyboardKeysAmount=0
AppTouchscreenKeyboardKeysAmountAutoFire=0
RedefinedKeysScreenKb="1 2 3 4 5 6 1 2 3 4"
MultiABI=n
AppVersionCode=101
AppVersionName="1.01"
CompiledLibraries="sdl_sound"
CustomBuildScript=n
AppCflags='-O2 -finline-functions'
AppLdflags=''
AppSubdirsBuild=''
AppUseCrystaXToolchain=n
AppCmdline=''
ReadmeText='^'

View File

@@ -0,0 +1,340 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
675 Mass Ave, Cambridge, MA 02139, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
Appendix: How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) 19yy <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) 19yy name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Library General
Public License instead of this License.

View File

@@ -0,0 +1,8 @@
simplemixer 1.1:
* Endian conversion after SDL_LoadWAV() is now
done on big endian platforms. (Oops...!)
* Added some sample format checking.
* Minor makefile cleanup
simplemixer 1.0:
* Initial release

View File

@@ -0,0 +1,28 @@
Simple Mixer
------------
This is about as simple as sound mixing gets.
Four voices, stereo volume control, 16 bit
mono sounds. It needs 44.1 kHz 16 bit stereo
output. (Won't resample, convert or anything.)
There's a primitive and utterly useless
pattern sequencer in there as well - you may
just ignore that code if you don't get it;
it's not important. Or you can make a GUI for
it and learn some SDL graphics coding in the
process, maybe...
The sounds were sampled by Michael Fischer,
from a real Roland TR-808 Rhythm Composer.
(A vintage analog drum machine.) Please see
README.SOUND for details. You may get the
rest of the sounds from here:
http://freeware.sgi.com/fw-5.3/fw_TR808/
Or just use Google, if that doesn't work.
David Olofson <david@olofson.net>

View File

@@ -0,0 +1,202 @@
=-=-=-=-=-=-=-=-=-=-=
Michael Fischer
of
T E C H N O P O L I S
=-=-=-=-=-=-=-=-=-=-=
Presents...
Roland TR-808 Rhythm Composer
Sound Sample Set 1.0.0 (09/08/94)
The Roland TR-808 (popularly known as the "808") is, perhaps, the most
popular analogue electronic drum machine of all time. Since its debut
in 1982, it has been the drum machine used the most by dance, pop, rap,
and rhythm and blues artists to produce the drum rhythm tracks for their
songs. (The famous cowbell sound at the beginning of Whitney Houston's
"I Wanna' Dance with Somebody", or the famous bass drum sound that
vibrates the ground when a car playing loud rap music drives by) Without
a doubt, the Roland TR-808 Rhythm Composer is a "classic beat box".
In recent years, many electronic musical instrument companies (Roland
and many others...) and studio engineer types have attempted to capture
its timeless sound through the use of sampling. This has however,
proven to be an often disappointing endeavour, due the the analogue
nature of the "808". Because the "808" is a truly "analogue" drum
machine, with very many (22 to be exact) knobs for the settings for its
drum sounds, sampling the unit often yields sample sets which are too
discrete (i.e. too "static" and too "limited" in variation) and simply
do not do justice to the wide sound range the "808" can produce. As a
result, people still, to this day, are in hot pursuit of real "808"'s,
and its U.S. dollar resale value today ($250 - $1,000) is often not too
far off from its U.S. dollar retail price at its introduction more than
a decade ago ($1,000).
I sincerely believe I have made major progress in narrowing the
difference between owning a real "808" and owning samples of one. When
put to proper use, these samples can be considered better than using a
real "808". Unlike a real "808", with these samples one can have the
certain drum sounds playing simultaneously that cannot do so on a real
"808", (Hand Claps and Maracas, for example.) as well as scale the
velocities of the sounds, and even apply grooves and timing to the beat
in a manner much more sophisticated and clearly beyond the capabilities
of a real "808". With the right sampler, these "808" samples can, for
all practical purposes, make a real "808" obsolete. I feel these samples
are of higher quality than those found in current commercial drum
machines. I feel these "808" samples are of higher quality than any
currently offered by commercial sample vendors. Quite frankly, I feel
this is the best overall sound sample set of the TR-808 to date. And
best of all, and very unlike many of the "competiting" samples, these
samples are ABSOLUTELY FREE!
What I have attempted to do is create a high quality sound sample set of
the "808" that is so comprehensive in sample range, that even the
"analogue purist" (the types who are actively pursing real "808"'s still
today...) would be satisfied. I have, through very time consuming,
painstaking sampling and sample editing work, using professional grade
equipment, sampled the "808" at five (see "FILENAME INFO" near the end
of this text file...) uniformly spaced positions for each sound modifier
knob. ("LEVEL" being the only exception---as I always kept "LEVEL" at
full to maintain the best signal to noise ratio.) As a result, this
rather comprehensive "808" sound sample set has the following :
25 Bass Drum sounds
25 Snare Drum sounds
5 Low Tom sounds
5 Mid Tom sounds
5 Hi Tom sounds
5 Low Conga sounds
5 Mid Conga sounds
5 Hi Conga sounds
1 Rim Shot sound
1 Claves sound
1 Hand Clap sound
1 Maracas sound
1 Cow Bell sound
25 Cymbal sounds
5 Open Hi Hat sounds
1 Closed Hi Hat sound
...making for a grand total of 116 sound samples of the Roland TR-808
Rhythm Composer!
These samples were taken _DIRECTLY_ from a Roland TR-808 Rhythm Composer
(SERIAL NO. 103852). They are _NOT_ samples of samples (i.e. sampled
from a recent drum machine, such as the Boss DR-660, Roland R-8,
R-8MkII, etc...) In other words, these samples were taken from a REAL
TR-808. All samples were recorded from the individual sound outputs (I
did NOT use the "HI" or "LO" "LEVEL" "MASTER OUT"puts!). While being
recorded, each sound (on the TR-808) was at highest volume level (with
all other volume levels set to the lowest possible setting), and the
master volume (on the TR-808) was always at the lowest setting. All
samples were made using SoundEdit 16 1.0.0 on a Macintosh Quadra 660AV.
EACH and EVERY sample is at 16-Bit, 44.1kHz resolution and was CAREFULLY
generated, sampled, selected (I recorded many hits of the same
sound, and picked the one that I felt best represented the average of
that particular sound) and edited.
Please enjoy this timeless sample set, and feel free to send me your
comments (positive or negative).
Most Sincerely,
Michael Fischer
Technopolis
(810) 650-6396
fischer1@student.msu.edu
=-=-=-=-=-=-=
FILENAME INFO
=-=-=-=-=-=-=
Bass Drum sounds start with "BD".
Snare Drum sounds start with "SD".
Low Tom sounds start with "LT".
Mid Tom sounds start with "MT".
Hi Tom sounds start with "HT".
Low Conga sounds start with "LC".
Mid Conga sounds start with "MC".
Hi Conga sounds start with "HC".
Rim Shot sound starts with "RS".
Claves sounds starts with "CL".
Hand Clap sound starts with "CP".
Maracas sound starts with "MA".
Cowbell sound starts with "CB".
Cymbal sounds start with "CY".
Open Hi Hat sounds start with "OH".
Closed Hi Hat sound starts with "CH".
These two letter abbreviations which determine what the filename begins
with are the exact ones used to abbreviate the sound names on the actual
TR-808 instrument select dial.
The "LEVEL" knob does not count as a knob in filenames, as it
was always at the maximum setting (to maintain the highest signal to
noise ratio.)
On the TR-808, each knob involved in the
composition/generation/synthesis of a particular drum sound has 11
uniformly spaced position marks on it (the positions on the dials are
not numbered, however...and hopefully the synthesis variable they
control is linearly distributed with respect to the knob position!) I
consider these 11 marks to be "0" through "10". Due to the fact that
the "0" position and the "10" position are the minimum (most
counter-clockwise) and maximum (most clockwise) positions, one may
consider "0" to be the minimum setting and "10" to be the maximum
setting. I decided to use dial positions "0" (minimum), "2.5", "5.0"
(middle), "7.5" and "10.0" (maximum) for my samples. As a result, I
decided upon the following naming convention :
"<filename>00.<file extension>" would be a file whose first (and only,
in this case) knob was set to 0.0 (or the minimum position).
"<filename>25.<file extension>" would be a file whose first (and only,
in this case) knob was set to 2.5.
"<filename>50.<file extension>" would be a file whose first (and only,
in this case) knob was set to 5.0 (or the middle position).
"<filename>75.<file extension>" would be a file whose first (and only,
in this case) knob was set to 7.5.
"<filename>10.<file extension>" would be a file whose first (and only,
in this case) knob was set to 10.0 (or the maximum position). It does
NOT mean the knob was set to 1.0!
Example : Low Tom with "TUNING" knob set to middle position would be
"LT50.<file extension>". If the file happened to be a ".WAV" ("WAVE")
file, the name would be "LT50.WAV".
For sounds which had TWO knobs, such as the Bass Drum, Snare Drum, and
Cymbal...
The naming convention is the same, but with two additional setting
position numbers after the first two...
Example : Bass Drum with "TUNING" knob set between the minimum and
middle position and "DECAY" set halfway between the middle and maximum
position would be "BD2575.<file extension>". If the file happened to be
a ".WAV" ("WAVE") file, the name would be "BD2575.WAV".
Once again, this naming convention was used for ALL the samples.
Of importance is the following :
* In filenames, "TONE" and "TUNING" come before "DECAY" and "SNAPPY".
Once again, please enjoy, and please do send me feedback on what you
think of these samples.
Sincerely,
Michael Fischer
Technopolis
(810) 650-6396
fischer1@student.msu.edu

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

View File

@@ -0,0 +1,15 @@
CC = gcc
CLIBS = $(shell sdl-config --libs)
CFLAGS = -O3 -Wall $(shell sdl-config --cflags)
SOURCES = simplemixer.c
all: simplemixer
clean:
rm -f *.o
rm simplemixer
simplemixer: ${SOURCES}
${CC} ${CFLAGS} -o simplemixer ${SOURCES} ${CLIBS}

View File

@@ -0,0 +1,288 @@
/*
* SimpleMixer 1.1
*
* Simple sound mixing example for SDL.
*
* (C) David Olofson, 2003
*/
#include <stdlib.h>
#include <signal.h>
#include "SDL.h"
#include "SDL_audio.h"
#define SM_SOUNDS 4
#define SM_VOICES 4
typedef struct
{
Uint8 *data;
Uint32 length;
} SM_sound;
typedef struct
{
Sint16 *data;
int length;
int position;
int l_vol;
int r_vol;
} SM_voice;
SM_sound sounds[SM_SOUNDS];
SM_voice voices[SM_VOICES];
SDL_AudioSpec audiospec;
int die = 0;
void sm_play(unsigned voice, unsigned sound, float lvol, float rvol)
{
if(voice >= SM_VOICES || sound >= SM_SOUNDS)
return;
/* Stop voice */
voices[voice].data = NULL;
/* Reprogram */
voices[voice].length = sounds[sound].length / 2;
voices[voice].position = 0;
voices[voice].l_vol = (int)(lvol * 256.0);
voices[voice].r_vol = (int)(rvol * 256.0);
/* Start! */
voices[voice].data = (Sint16*)(sounds[sound].data);
}
static void sm_mixer(void *ud, Uint8 *stream, int len)
{
int vi, s;
Sint16 *buf = (Sint16 *)stream;
/* Clear the buffer */
memset(buf, 0, len);
/* 2 channels, 2 bytes/sample = 4 bytes/frame */
len /= 4;
/* For each voice... */
for(vi = 0; vi < SM_VOICES; ++vi)
{
SM_voice *v = &voices[vi];
if(!v->data)
continue;
/* For each sample... */
for(s = 0; s < len; ++s)
{
if(v->position >= v->length)
{
v->data = NULL;
break;
}
buf[s * 2] += v->data[v->position] * v->l_vol >> 8;
buf[s * 2 + 1] += v->data[v->position] * v->r_vol >> 8;
++v->position;
}
}
}
int sm_open(void)
{
SDL_AudioSpec as;
memset(sounds, 0, sizeof(sounds));
memset(voices, 0, sizeof(voices));
if(SDL_InitSubSystem(SDL_INIT_AUDIO|SDL_INIT_VIDEO) < 0)
return -2;
as.freq = 44100;
as.format = AUDIO_S16SYS;
as.channels = 2;
as.samples = 1024;
as.callback = sm_mixer;
if(SDL_OpenAudio(&as, &audiospec) < 0)
return -3;
if(audiospec.format != AUDIO_S16SYS)
return -4;
SDL_PauseAudio(0);
return 0;
}
void sm_close(void)
{
int i;
SDL_PauseAudio(1);
for(i = 0; i < SM_VOICES; ++i)
voices[i].data = NULL;
SDL_CloseAudio();
for(i = 0; i < SM_SOUNDS; ++i)
SDL_FreeWAV(sounds[i].data);
memset(sounds, 0, sizeof(sounds));
memset(voices, 0, sizeof(voices));
}
void flip_endian(Uint8 *data, int length)
{
int i;
for(i = 0; i < length; i += 2)
{
int x = data[i];
data[i] = data[i + 1];
data[i + 1] = x;
}
}
int sm_load(int sound, const char *file)
{
int failed = 0;
SDL_AudioSpec spec;
if(sounds[sound].data)
SDL_FreeWAV(sounds[sound].data);
sounds[sound].data = NULL;
if(SDL_LoadWAV(file, &spec, &sounds[sound].data,
&sounds[sound].length) == NULL)
return -1;
if(spec.freq != 44100)
fprintf(stderr, "WARNING: File '%s' is not 44.1 kHz."
" Might sound weird...\n", file);
if(spec.channels != 1)
{
fprintf(stderr, "Only mono sounds are supported!\n");
failed = 1;
}
switch(spec.format)
{
case AUDIO_S16LSB:
case AUDIO_S16MSB:
if(spec.format != AUDIO_S16SYS)
flip_endian(sounds[sound].data, sounds[sound].length);
break;
default:
fprintf(stderr, "Unsupported sample format!\n");
failed = 1;
break;
}
if(failed)
{
SDL_FreeWAV(sounds[sound].data);
sounds[sound].data = NULL;
return -2;
}
return 0;
}
void breakhandler(int a)
{
die = 1;
}
int main(int argc, char *argv[])
{
const char *bd = "#...#...#...#..##...#...#...#.##";
const char *cl = "....#..*....#....*..#....*..#.**";
const char *cb = "#...*..#..*...#.#...*..#..*..*#*";
const char *hh = "..#...#...#...#...#...#...#...#.";
int res;
Uint32 step = 0;
Sint32 timer;
SDL_Event event;
int color = 0;
if(SDL_Init(0) < 0)
return -1;
/*
atexit(SDL_Quit);
signal(SIGTERM, breakhandler);
signal(SIGINT, breakhandler);
*/
if(sm_open() < 0)
{
fprintf(stderr, "Couldn't start mixer!\n");
SDL_Quit();
return -1;
}
SDL_SetVideoMode(320, 200, 16, SDL_SWSURFACE);
res = 0;
res |= sm_load(0, "808-bassdrum.wav");
res |= sm_load(1, "808-clap.wav");
res |= sm_load(2, "808-cowbell.wav");
res |= sm_load(3, "808-hihat.wav");
if(res)
{
sm_close();
SDL_Quit();
fprintf(stderr, "Couldn't load sounds!\n");
return -1;
}
/*
* Of course, playing this stuff would be
* much better done in the audio callback,
* since the timing out here jitters a lot.
*
* However, this is just a fun hack to get
* the thing to make some sound, without
* slapping in a game or something. :-)
*/
SDL_Delay(200);
timer = (Sint32)SDL_GetTicks();
while(!die)
{
if('#' == bd[step])
sm_play(0, 0, 1.0, 1.0);
if('#' == cl[step])
sm_play(1, 1, 0.6, 0.5);
else if('*' == cl[step])
sm_play(1, 1, 0.2, 0.3);
if('#' == cb[step])
sm_play(2, 2, 0.3, 0.2);
else if('*' == cb[step])
sm_play(2, 2, 0.1, 0.2);
if('#' == hh[step])
sm_play(3, 3, 0.3, 0.4);
step = (step + 1) % 32;
timer += 120;
while(SDL_PollEvent(&event) > 0)
{
if(event.type & (SDL_KEYUP | SDL_KEYDOWN))
{
Uint8 *keys = SDL_GetKeyState(NULL);
if(keys[SDLK_ESCAPE])
die = 1;
}
}
SDL_FillRect(SDL_GetVideoSurface(), NULL, color);
color += 10;
SDL_Flip(SDL_GetVideoSurface()); // Program is required to call SDL_Flip(), or it will invoke Application Not Responding dialog
while(((Sint32)SDL_GetTicks() - timer) < 0)
SDL_Delay(10);
}
sm_close();
SDL_Quit();
return 0;
}