2. Sound
openFrameworks has some great support for
playing sounds. Using the ofSoundPlayer class you
call loadSound once to load the sound file (i.e.
mp3, wav) then call play to start playing.
Using ofSoundStream you can generate sounds or
use a microphone to get an input stream.
3. Playing sounds
Put a sound file into your data directory and use an
ofSoundPlayer to play the file.
testApp.h testApp.cpp
class testApp : public ofBaseApp{
public: void testApp::setup(){
ofSoundPlayer my_sound;
my_sound.loadSound("clong.mp3");
ofSoundPlayer my_singer; }
}
void testApp::keyReleased(int key){
my_sound.play();
}
4. Multi play
A ofSoundPlayer can play the same sound object
multiple times simultaniously by setting the
multiplay flag. Call setMultiPlay(bool) to set
multiplay on or off. With the code below, try
pressing your space bar multiple times.
void testApp::setup(){
ofBackground(33,33,33);
my_sound.loadSound("clong.mp3");
my_singer.loadSound("violet.mp3");
my_sound.setMultiPlay(true);
my_singer.setMultiPlay(true);
}
void testApp::keyReleased(int key){
my_sound.play();
}
5. Volume and panning
To change the volume of a single sound use
my_sound.setVolume(float). A value of 0.0 means
no sound, 1.0 full volume. To pan the sound from
left to right use my_sound.setPan(float). A value of
-1.0 means play only left speaker, a value of 1.0
means play only right speaker.
void testApp::mouseReleased(int x, int y, int button){
if(button == 0) {
my_sound.setPan(-1.0);
}
else {
my_sound.setPan(1.0);
}
}
6. Pause
To temporarily stop a sound you call
my_sound.setPaused(bool).
void testApp::keyReleased(int key){
if(key == 'p') {
my_sound.setPaused(true);
}
}
7. Loop
If you want the sound to repeat over an d over set
it to loop mode using my_sound.setLoop(bool).
void testApp::keyReleased(int key){
if(key == 'l') {
my_sound.setLoop(true);
}
}
8. Changing the speed
With my_sound.setSpeed(float) you change how
fast the sound is played back. A value near 0.0 is
really slooooww and the higher the faster.
void testApp::keyReleased(int key){
if(key == 'n') {
my_sound.setSpeed(0.1f);
}
else if(key == 'g') {
my_sound.setSpeed(40.0f);
}
}
9. Set position
Using my_sound.setPosition(float) you can scrub
the playhead. A value of 0.0 brings you to the start
of the sound. Value 1.0 to the end.
void testApp::update(){
my_sound.setPosition((float)ofGetMouseX()/ofGetWidth());
}
12. Generating sounds
With the ofSoundStream class you can generate
sound or get sound from a microphone into your
application file.
Starting with OF-007 we have a new function in
our testApp called audioIn. This function is called
periodically with samples from the input device.
13. Generating sounds
To get input from a microphone you call setup(...)
and create an audioIn(..) function.
testApp.h
class testApp : public ofBaseApp{
public:
ofSoundStream my_sstream;
void audioIn(float* input, int bufferSize, int nChannels);
}
testApp.cpp
void testApp::setup(){
my_sstream.setup(this, 0, 2, 44100, 256, 4);
}