tags:

views:

1915

answers:

6

I am experimenting with Beep function on Windows:

#include <windows.h>
...
Beep(frequency, duration);

The computer then beeps with some frequency for some duration. How would I do this on a Linux computer?

Edit: It IS important to output different frequencies.

A: 

try this link

Schwartser
A: 

I'm not familiar with Linux, but outputting ascii character 0x07 seems to do that trick from what I read with a quick google search.

Daniel
+6  A: 

Check out the source code for beep available with Ubuntu (and probably other distros) or have a look at http://www.johnath.com/beep/beep.c for another source (it's the same code, I believe).

It allows you to control frequency, length and repetitions (among other things) with ease.

paxdiablo
I believe you need root privs to tune the PC-Speaker beep specifics, at least under X you do.
Kent Fredric
Not with this code, I use it directly from a user account. I think the control is exposed by the standard device driver ioctl() interface.
paxdiablo
A: 

I'd suggest you look at the source for the beep utility. that does exactly what you want. (specifically, it opens "/dev/console" and uses ioctl to request beep. note this will only work on the attached console)

Hasturkun
+3  A: 

lets have us some gabba coming from the audio speakers

#!/usr/bin/ruby

$audio = File.open("/dev/audio", "w+")
def snd char
 $audio.print char.chr
end

def evil z
 0.step(100, 4.0 / z) { |i|
  (i / z).to_i.times { snd 0 }
  (i / z).to_i.times { snd 255 }
 }
end

loop {
 evil 1 
 evil 1
 evil 1
 evil 4
}

more seriously though:

//g++ -o pa pa.cpp -lportaudio
#include <portaudio.h>
#include <cmath>

int callback(void*, void* outputBuffer, unsigned long framesPerBuffer, PaTimestamp, void*) {
 float *out = (float*)outputBuffer;
 static float phase;
 for(int i = 0; i < framesPerBuffer; ++i) {
  out[i] = std::sin(phase);
  phase += 0.1f;
 }
 return 0;
}

int main() {
 Pa_Initialize();
 PaStream* stream;
 Pa_OpenDefaultStream(&stream, 0, 1, paFloat32, 44100, 256, 1, callback, NULL);
 Pa_StartStream(stream);
 Pa_Sleep(4000);
}
you should init the phase to 0.0 and maybe rewind it if it is bigger then 2pi, ie. if (phase > 2 * M_PI) phase -= 2 * M_PI, else you will come to the point, where phase + 0.1f == phase. I haven't calculated when this will happen tho :)
quinmars
good point. or phase could be integer, and I'd take sin(phase/10.0)
A: 

In summary:

  1. Outputting a BEL character to a terminal might produce a beep - depending on what terminal it is and what its configuration is. There is no control over this however.

  2. Any sound you like can be produced by outputting audio data to /dev/dsp or some other sound device. This includes beep, but making a sound involves playing back an actual sample.

  3. The console driver provides (in some configurations) an ioctl for /dev/console which beeps with a configurable pitch (much like the NT one)

MarkR