Beeper - loopable sound using Clip.

// <applet code='Beeper' width='300' height='300'></applet>
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.text.DecimalFormat;
import javax.sound.sampled.*;
import java.io.ByteArrayInputStream;
/** Beeper presents a small, loopable tone that can be heard
by clicking on the Code Key.  It uses a Clip to loop the sound,
as well as for access to the Clip's gain control.
@author Andrew Thompson
@version 2009-12-19
@license LGPL */
public class Beeper extends JApplet {
public void init() {
  getContentPane().add(new BeeperPanel());
  validate();
public static void main(String[] args) {
  SwingUtilities.invokeLater(new Runnable() {
   public void run() {
    JFrame f = new JFrame("Beeper");
    f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    BeeperPanel BeeperPanel = new BeeperPanel();
    f.setContentPane(BeeperPanel);
    f.pack();
    f.setMinimumSize( new Dimension(300,300) );
    f.setLocationRelativeTo(null);
    f.setVisible(true);
/** The main UI of Beeper. */
class BeeperPanel extends JPanel {
JComboBox sampleRate;
JSlider framesPerWavelength;
JLabel frequency;
JCheckBox harmonic;
Clip clip;
DecimalFormat decimalFormat = new DecimalFormat("###00.00");
BeeperPanel() {
  super(new BorderLayout());
  JPanel options = new JPanel();
  BoxLayout bl = new BoxLayout(options,BoxLayout.Y_AXIS);
  options.setLayout(bl);
  Integer[] rates = {
   new Integer(8000),
   new Integer(11025),
   new Integer(16000),
   new Integer(22050)
  sampleRate = new JComboBox(rates);
  sampleRate.setToolTipText("Samples per second");
  sampleRate.setSelectedIndex(1);
  JPanel pSampleRate = new JPanel(new BorderLayout());
  pSampleRate.setBorder(new TitledBorder("Sample Rate"));
  pSampleRate.add( sampleRate );
  sampleRate.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent ae) {
    setUpSound();
  options.add( pSampleRate );
  framesPerWavelength = new JSlider(JSlider.HORIZONTAL,10,200,25);
  framesPerWavelength.setPaintTicks(true);
  framesPerWavelength.setMajorTickSpacing(10);
  framesPerWavelength.setMinorTickSpacing(5);
  framesPerWavelength.setToolTipText("Frames per Wavelength");
  framesPerWavelength.addChangeListener( new ChangeListener(){
   public void stateChanged(ChangeEvent ce) {
    setUpSound();
  JPanel pFPW = new JPanel( new BorderLayout() );
  pFPW.setBorder(new TitledBorder("Frames per Wavelength"));
  pFPW.add( framesPerWavelength );
  options.add( pFPW );
  JPanel bottomOption = new JPanel( new BorderLayout(4,4) );
  harmonic = new JCheckBox("Add Harmonic", false);
  harmonic.setToolTipText(
   "Add harmonic to second channel, one octave up");
  harmonic.addActionListener( new ActionListener(){
   public void actionPerformed(ActionEvent ae) {
    setUpSound();
  bottomOption.add( harmonic, BorderLayout.WEST );
  frequency = new JLabel();
  bottomOption.add( frequency, BorderLayout.CENTER );
  options.add(bottomOption);
  add( options, BorderLayout.NORTH );
  JPanel play = new JPanel(new BorderLayout(3,3));
  play.setBorder( new EmptyBorder(4,4,4,4) );
  JButton bPlay  = new JButton("Code Key");
  bPlay.setToolTipText("Click to make tone!");
  Dimension preferredSize = bPlay.getPreferredSize();
  bPlay.setPreferredSize( new Dimension(
   (int)preferredSize.getWidth(),
   (int)preferredSize.getHeight()*3) );
  // TODO comment out to try KeyListener!
  bPlay.setFocusable(false);
  bPlay.addMouseListener( new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent me) {
     loopSound(true);
    @Override
    public void mouseReleased(MouseEvent me) {
     loopSound(false);
  play.add( bPlay );
  try {
   clip = AudioSystem.getClip();
   final FloatControl control = (FloatControl)
    clip.getControl( FloatControl.Type.MASTER_GAIN );
   final JSlider volume = new JSlider(
    JSlider.VERTICAL,
    (int)control.getMinimum(),
    (int)control.getMaximum(),
    (int)control.getValue()
   volume.setToolTipText("Volume of beep");
   volume.addChangeListener( new ChangeListener(){
    public void stateChanged(ChangeEvent ce) {
     control.setValue( volume.getValue() );
   play.add( volume, BorderLayout.EAST );
  } catch(Exception e) {
   e.printStackTrace();
  add(play, BorderLayout.CENTER);
  setUpSound();
/** Sets label to current frequency settings. */
public void setFrequencyLabel() {
  float freq = getFrequency();
  if (harmonic.isSelected()) {
   frequency.setText(
    decimalFormat.format(freq) +
    "(/" +
    decimalFormat.format(freq*2f) +
    ") Hz" );
  } else {
   frequency.setText( decimalFormat.format(freq) + " Hz" );
/** Generate the tone and inform the user of settings. */
public void setUpSound() {
  try {
   generateTone();
   setFrequencyLabel();
  } catch(Exception e) {
   e.printStackTrace();
/** Provides the frequency at current settings for
sample rate & frames per wavelength. */
public float getFrequency() {
  Integer sR = (Integer)sampleRate.getSelectedItem();
  int intST = sR.intValue();
  int intFPW = framesPerWavelength.getValue();
  return (float)intST/(float)intFPW;
/** Loops the current Clip until a commence false is passed. */
public void loopSound(boolean commence) {
  if ( commence ) {
   clip.setFramePosition(0);
   clip.loop( Clip.LOOP_CONTINUOUSLY );
  } else {
   clip.stop();
/** Generates a tone, and assigns it to the Clip. */
public void generateTone()
  throws LineUnavailableException {
  if ( clip!=null ) {
   clip.stop();
   clip.close();
  } else {
   clip = AudioSystem.getClip();
  boolean addHarmonic = harmonic.isSelected();
  int intSR = ((Integer)sampleRate.getSelectedItem()).intValue();
  int intFPW = framesPerWavelength.getValue();
  float sampleRate = (float)intSR;
  // oddly, the sound does not loop well for less than
  // around 5 or so, wavelengths
  int wavelengths = 20;
  byte[] buf = new byte[2*intFPW*wavelengths];
  AudioFormat af = new AudioFormat(
   sampleRate,
   8,  // sample size in bits
   2,  // channels
   true,  // signed
   false  // bigendian
  int maxVol = 127;
  for(int i=0; i<intFPW*wavelengths; i++){
   double angle = ((float)(i*2)/((float)intFPW))*(Math.PI);
   buf[i*2]=getByteValue(angle);
   if(addHarmonic) {
    buf[(i*2)+1]=getByteValue(2*angle);
   } else {
    buf[(i*2)+1] = buf[i*2];
  try {
   byte[] b = buf;
   AudioInputStream ais = new AudioInputStream(
    new ByteArrayInputStream(b),
    af,
    buf.length/2 );
   clip.open( ais );
  } catch(Exception e) {
   e.printStackTrace();
/** Provides the byte value for this point in the sinusoidal wave. */
private static byte getByteValue(double angle) {
  int maxVol = 127;
  return (new Integer(
   (int)Math.round(
   Math.sin(angle)*maxVol))).
   byteValue();
}

This code was written (rather belatedly) in response to a question in [Example: Code to generate audio tone|http://forums.sun.com/thread.jspa?threadID=5243872]. Due to it's age, it has been locked.
The replier wanted to know how to use JavaSound for a Morse code key. Actually now I think about it, the sound loops nicely, but it still demonstrates a slight click at start and stop. I tried using Clip.loop(0) to stop the sound, but that did not avoid the 'click'! I suppose you would need to do as the person was musing, and adjust the GAIN of the Clip up and down.
In any case - questions.
- Can anyone make this work for key presses? The first thing you'd need to do is a find on "TODO" and comment out the line that ensures the Code Key is not focusable (and then add a KeyListener(1)). The problem I encountered was that the KeyEvents were getting fired continuously, which caused the sound to 'stutter'. A Timer to ignore quickly repeated keys might work (though I could not make it work for me), but then that would introduce a lag between when whe key was released, and when the sound stopped. It would need to be a very short delay, to use it much in the way the mouse click currently works.
- Any ideas on improvements to the basic code? (1) (I will be adding the ability to configure the parameters of the applet - more code lines. Possibly also converting the GAIN control from the mostly useless logarithmic ..whatever scale it uses, to linear.)
1) Note that I had to use single spaces to indent - everything else blew the posting limit(2).
2) Hence also, questions on 2nd post. ;)
To compile and run as an applet/application (in a recent SDK).
javac Beeper.java
appletviewer Beeper.java
java BeeperEdit 1:
Latest source can be found at [http://pscode.org/test/eg/Beeper.java]. See also the [formatted version|http://pscode.org/fmt/sbx.html?url=%2Ftest%2Feg%2FBeeper.java&col=2&fnt=2&tab=2&ln=0].
Edited by: AndrewThompson64 on Dec 19, 2009 1:50 PM

Similar Messages

  • Change volume and Balance of speaker using Clip interface

    Hello,
    I am playing more than one Clip simulteniously. I want to change the volume and balance of individual Clip so that they have individual effect on speaker. I mean, if there are two clip then one should have high sound and other have low like that.
    Any help would be appreciated.
    Thanks in Advance.

    Hello,
    I play a sound using Clip interface in Java Sound. i am able to get FloatControl.Type.MASTER_GAIN) control but not FloatControl.Type.PAN)
    I have written a code like this,
    FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.PAN);
    Any help would be appreciated.
    * Thanks In advance*

  • Erratic sound playback using Clip (javax.sound.samled)

    Hi,
    I have recently delved into writing an application with sound using Scala. Sound does play but seems rather unreliable across systems. For instance, only the long sounds are audible on my Ubuntu 9.04 system (OpenJDK 6b14-1.4.1-0ubuntu11). Interestingly on my windows PC running Vista Home with Sun JRE (build 6.1.0_15-b3) only the short sounds are audible and the longer sounds are cut off.
    Before reporting bugs at OpenJDK and Sun respectively I would like to know if there is anything that I need to pay extra attention to. My programs "play" method is as follows:
    Tuple2 sound = audioResources(name)
    Clip clip = AudioSystem.getLine(sound.getInfo()).asInstanceOf[Clip]
    AudioInputStream stream = AudioSystem.getAudioInputStream(new ByteArrayInputStream(sound sound.getByteArray()))
    clip.open(stream)
    clip.start()Have adapted my code from Scala to Java somewhat. I am assuming that clip.start() works asynchronously. Hope can give me some pointers on how to get this to work correctly.
    Best,
    Dirk Louwers

    Well, that's kind of a weird way of doing that... I would have done...
    Clip c = AudioSystem.getClip();
    AudioInputStream stream = AudioSystem.getAudioInputStream(new ByteArrayInputStream(sound sound.getByteArray()));
    clip.open(stream);
    clip.start();Anyway, clip.start() does work asyncronously, so you'll want to make sure your program isn't terminating before the clip has time to play.

  • Dratted Beep Boop sound

    I am a newbie at this build your own PC thing, and would appreciate advice from you experts.  I bought an ANTEC Sonata case and I believe that the power supply it comes with is rated 380 watts. I installed a K7N2G-IL board, with an AMD Athlon XP2500 processor, 333 FSB, Barton Core, It has 512 MB, DDR Ultra memory, 400 Mhz single channel for now. Installed a single CDRW/DVD Combo drive, and am just using the onboard sound and video for now. Much to my  delight when I booted it up everything came on and seems to work great. I will add to video and sound cards and memory later, that's part of the fun of build your own.  Here's the problem:  The periodic beep/ boop sound from the PC speaker is driving me nuts.  The BIOS is Phoenix Award version 3.5.  After reading some of you FAQ's I have gone in and turned off (disabled ) the warning Beep in the BIOS. It reports the CPU temp as 37 deg. C; System Temp as 35 deg. C; voltages seem resonable at:  +12 V = 11.67; - 12 V = - 11.95; + 5 V = 4.94; and - 5 V = -4.94.  I could not find a seperate place in the BIOS to turn off what is referred to as "case intrusion?".  What can I do to stop the infernal beeps, short of disconnecting the case speaker?
    I double checked after reboot, and the warning beep option remained disabled.  Any and all helpful hints are appreciated.
    BobB

    Thanks for your responses,
    I wouldn't call it a chirp,  it's a solid single frequency tone for several seconds, followed by a second different solid frequency for several seconds.  The two tones do not repeat, and will not be heard for maybe 15 or 20 minutes.
    Come to think of it, I have not heard the tones while I was in the BIOS, or when booting,  only while in windows.  But they are definatlely coming from the PC speaker, and not fromthe windows speakers at the other end of the desk.
    The Antec case has two keyed latches, but I don't remember seeing any wires going to them. I think they are stricktly mechanical. When I get home from work tonight I'll read throuugh the manual to see if I can find mention of intrusion detection, but I don't remember seeing it when I was putting things together.
    Thanks again.
    BobB

  • How do I use clipping mask to cover unwanted background?

    I'm practicing illustrator myself. I have a book for illustrator hoping it would show me step by step on how to use the masks to take away any unwanted background in a photo but it didn't do that. Can anyone teach me how or show me where to look for the information on how to use the clipping masks or other type of masks? I went to the adobe workshop video to look for the answer but it didn't show exactly as what i want to know. The image i'm practicing on is a family photo and i want to isolate everything to just one person in the photo so how can I do that using clipping mask? Thanks!!

    oh~~~ so i still need to use pen tool to draw the shape out. I thought there's something i could use to make the shape easily. Stupid me XD
    I was wondering if you could help me more...can you give me a rule of thumb like when is best to use illustrator to edit image or photoshop?
    Thanks for your tip! I really appreciate it!!
    =D
    Sometimes the only way to stay sane is to go a little crazy. -
    "Girl, Interrupted"
    It is the journey itself which makes up your life. -
    Tiresias, the blind prophet, "The Odyssey"
    Date: Thu, 18 Feb 2010 02:00:41 -0700
    From: [email protected]
    To: [email protected]
    Subject: How do I use clipping mask to cover unwanted background?
    Draw the mask using the pen tool over the image. Select both the drawn mask AND image and choose Object > Clipping Mask > Make
    >

  • I am unable to get sound using apogee jam with my guitar. I can see input levels but no sound. What step am I missing?

    I am unable to get any sound using apogee jam with my guitar in logic pro 9. I am using Macbook pro.

    status...      
    DWdrummerBeam  
            Jun 4, 2012 3:24 PM    
    I think I have done something wrong. I used my Apogee Jam on a guitar project with several audio tracks in Logic Pro 9. And while the Apogee Jam still was connected, I switched to another project with only instrument tracks (synths). I forgot to change the "Built In Input". After I did this, my guitar sounds like crap when I try to use Apogee Jam in the same guitar project, or also if I create a new project. I use Guitar Rig 5 (Native Instruments) as my guitar plug-in. But the guitar sounds strange even if I don´t assign Guitar Rig.
    Can somebody help me?

  • I unplug my MacBook Pro from power and external speaker and I hear incremental beeps and sounds as if email being sent. Doesn't' stop until I close email

    I unplug my MacBook Pro from power and external speaker and I hear  incremental beeps and sounds as if email being sent. Doesn't' stop until I close email.   Not sure what is happening our what if any emails are being sent.

    You can install Temperature Monitor and have a look if the CPU oder GPU oder something else went to hot. The processor has a built in safety mechanism to shut down the computer before taking damage.

  • Can't record sound using the jack in/out on macbook pro 13 os x

    hi
    i bought a new macbook pro 13' intel core i5 4gb with the latest os x version 10.8.2. mainly for sound and video editing
    yesterday i tried to record sound using garage band and through the mini jack port. once i connected an mp3 player to the mini jack port, the sound prefrences window recognized it as headphones and not as input jack as it did on my friend's same mac with leopard os on it.
    it seems like no matter what i try to do (changing instument set up on garage band, restarting the computer with the jack in or out etc...) nothing worked
    i bought this mac just so i wouldn't have to deal with these kind of problems....suppose to be a very user friendly os and hardwear.
    very dissapointing. please if any one has a clue what can be done?

    i'm aware of my other audio interface options, but i would expact this machine to have the basic options every 20 year old pc has, a simple plug and play difault to get audio into my computer. i bought it at b and h in NY and in their specs it says that it's a 'combo kack' - meaning both in and out analog audio ports. after cheaking mac's site it says only headphones.
    also tryied to connect a digidesign mini mbox2, through the usb port, and i had to unplug it, shut down the mbp, restart it again etc.. and it also doesn't always work propely and makes all kinds of digital error sounds.
    although in this case i can't that the mbox is not damaged.
    over all it's very dissapointing. it's my first mac and i figured it would be a much more idiot proof, user freindly work tool.
    if you got any other tips i'd appreciate that
    thanx alot for the focusrite link

  • How do I turn off Sleep/Hibernation/Startup Beeps and Sounds?

    I have a Lenovo Thinkpad x200 running vista ultimate. type 7454-cto
    How do i turn off these annoying beeps that sound every time my computer goes into and out of sleep and hibernation.
    I've tried turning the sound scheme to "No sounds," but the beep still sounds when computer enters and exits sleep and hibernation.
    If i turn on "mute" before i enter sleep or hibernate, the beep does not sound (which is what i want). Unfortunately, its impossible to turn on MUTE when im trying to bring the computer out of sleep or hibernate (which makes it very distracting to turn the computer on during class). 
    Solution:
    Enter BIOS by pressing F1 during boot
         >Config
                  >Beep and Alarm
                             Set Power control beep to [Disabled]
    Message Edited by ender63071 on 09-18-2008 03:36 PM
    Solved!
    Go to Solution.

    Just tried it out and the BIOS solution works.  Here's the funny part: After disabling the beep in BIOS config, I started windows and opened Power Manager again.  Sure enough, the "beep when power state changes" option was finally disabled.  Just for kicks, I tried to see if I could enable it again in Power Manager.  I enabled it just fine in Power Manager but when I tried to disable it again I COULDN'T!  I had to back into the BIOS again to disable it.  So the deal seems to be that Power Manager will allow you to turn on the annoying beep, but if you want to turn it off, you need to do it in the BIOS settings.

  • HOW TO USE CLIPS FROM A DVD???

    HOW TO USE CLIPS FROM A DVD???
    i know this may be a stupid and obvious question but i can't seem to figure it out.
    these are not copyrited dvds... mostly home movies and old home movies put onto dvd.
    thank you... much appreciated.

    Studio X has given one suggestion.
    MPEG Streamclip is another:-
    http://www.squared5.com/
    It is free but your computer may not have the QT MPEG 2 Playback Component which costs $20 from Apple as a download.
    If you have access to an Analogue-DV converter you can use that. Also a DV camcorder which has Analogue IN.
    If you have Final Cut Pro installed, you will have the QT component.
    Message was edited by: Ian R. Brown

  • Is there a way to automatically hide used clips??

    is there a way to hide the used clips??
    iMovie 10.0.4

    You can capture the complete clip and then apply Mark > DV Start/Stop Detect over the captured clip. You could get the best of two worlds so: smooth capture and clips creation.

  • How To Record Sound Using Applet

    How To Record Sound Using JApplet

    Hallo there,
    I am intrested on the same topic but I am not so good to modify the sound sdk demo. Is there anyone willing to share some code?
    Thanks
    Matteo

  • What is the benefit of using clipping paths for a knock out?

    I found a posting saying they need someone to knock out the background of a lot of images using clipping paths. My question is, WHY use a clipping path? I know the rule of not using a selection tool such as the Magic Wand and then turning it into a clipping path and I know why that is. But if all is needed is for the background to be knocked out, why can't we just use the selection tool in the first place and just knock out the background from there? What is the benefit of that clipping mask?

    Usually the term Clipping Path refers to turning a path into a clipping path (in the paths panel) for use in older programs such as PageMaker that don't support transparency.
    For example if one wanted to import a file into PageMaker and only have a certain part of the document visible, one would make a path (or selection) around the object
    and turn the path (or selection) into a clipping path. Sorta the same results you see in photoshop using a layer mask or vector mask.
    Also clipping paths are used in certain printing workflows.
    Without seeing the posting it's hard to say what they meant and in photoshop 6 vector masks were labeled as Layer Clipping Paths not to be confused with real clipping paths.
    Old versions of photoshop also used the term Group With Previous to denote Create Clipping Mask.
    photoshop 6:
    Photoshop cs6:
    Anyway clipping masks and clipping paths are two different things in photoshop.
    layer masks, vector masks and clipping masks:
    http://helpx.adobe.com/content/help/en/photoshop/using/masking-layers.html
    an example of creating a clipping path:
    http://www.clippingpathspecialist.com/tutorials.html

  • AI CS6 vectors turn into embedded image when using clipping mask

    AI CS6 vectors turn into embedded image when using clipping mask, how to solve it?

    With the Clipping Mask selected go here

  • Where has "Duplicate Project + Used Clips" gone in 10.2 ?

    I want to backup my project and all the media it uses to an external hard drive.
    In 10.1 I could use, Duplicate Project + Used Clips , but where is that in 10.2?

    I'm assuming you mean 10.1.2, not 10.0.2. For the recent version, connect the external drive. Make a new library on it and set the library properties to be managed media, so the media in inside the library. Drag the project from the existing event on your drive to the event on the external drive, that will copy the project and the used media to that event. You'll also have the option to copy render and optimized media. I'd forget about that. Mail the drive and your colleague should be good to go.

Maybe you are looking for