Example: Code to generate audio tone

This code shows how to generate and play a simple sinusoidal audio tone using the javax.sound.sampled API (see the generateTone() method for the details).
This can be particularly useful for checking a PCs sound system, as well as testing/debugging other sound related applications (such as an audio trace app.).
The latest version should be available at..
<http://www.physci.org/test/sound/Tone.java>
You can launch it directly from..
<http://www.physci.org/test/oscilloscope/tone.jar>
Hoping it may be of use.
package org.physci.sound;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.LineUnavailableException;
import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JSlider;
import javax.swing.JCheckBox;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;
import java.net.URL;
Audio tone generator, using the Java sampled sound API.
@author andrew Thompson
@version 2007/12/6
public class Tone extends JFrame {
  static AudioFormat af;
  static SourceDataLine sdl;
  public Tone() {
    super("Audio Tone");
    // Use current OS look and feel.
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            SwingUtilities.updateComponentTreeUI(this);
        } catch (Exception e) {
            System.err.println("Internal Look And Feel Setting Error.");
            System.err.println(e);
    JPanel pMain=new JPanel(new BorderLayout());
    final JSlider sTone=new JSlider(JSlider.VERTICAL,200,2000,441);
    sTone.setPaintLabels(true);
    sTone.setPaintTicks(true);
    sTone.setMajorTickSpacing(200);
    sTone.setMinorTickSpacing(100);
    sTone.setToolTipText(
      "Tone (in Hertz or cycles per second - middle C is 441 Hz)");
    sTone.setBorder(new TitledBorder("Frequency"));
    pMain.add(sTone,BorderLayout.CENTER);
    final JSlider sDuration=new JSlider(JSlider.VERTICAL,0,2000,1000);
    sDuration.setPaintLabels(true);
    sDuration.setPaintTicks(true);
    sDuration.setMajorTickSpacing(200);
    sDuration.setMinorTickSpacing(100);
    sDuration.setToolTipText("Duration in milliseconds");
    sDuration.setBorder(new TitledBorder("Length"));
    pMain.add(sDuration,BorderLayout.EAST);
    final JSlider sVolume=new JSlider(JSlider.VERTICAL,0,100,20);
    sVolume.setPaintLabels(true);
    sVolume.setPaintTicks(true);
    sVolume.setSnapToTicks(false);
    sVolume.setMajorTickSpacing(20);
    sVolume.setMinorTickSpacing(10);
    sVolume.setToolTipText("Volume 0 - none, 100 - full");
    sVolume.setBorder(new TitledBorder("Volume"));
    pMain.add(sVolume,BorderLayout.WEST);
    final JCheckBox cbHarmonic  = new JCheckBox( "Add Harmonic", true );
    cbHarmonic.setToolTipText("..else pure sine tone");
    JButton bGenerate = new JButton("Generate Tone");
    bGenerate.addActionListener( new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          try{
            generateTone(sTone.getValue(),
              sDuration.getValue(),
              (int)(sVolume.getValue()*1.28),
              cbHarmonic.isSelected());
          }catch(LineUnavailableException lue){
            System.out.println(lue);
    JPanel pNorth = new JPanel(new BorderLayout());
    pNorth.add(bGenerate,BorderLayout.WEST);
    pNorth.add( cbHarmonic, BorderLayout.EAST );
    pMain.add(pNorth, BorderLayout.NORTH);
    pMain.setBorder( new javax.swing.border.EmptyBorder(5,3,5,3) );
    getContentPane().add(pMain);
    pack();
    setLocation(0,20);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    String address = "/image/tone32x32.png";
    URL url = getClass().getResource(address);
    if (url!=null) {
      Image icon = Toolkit.getDefaultToolkit().getImage(url);
      setIconImage(icon);
  /** Generates a tone.
  @param hz Base frequency (neglecting harmonic) of the tone in cycles per second
  @param msecs The number of milliseconds to play the tone.
  @param volume Volume, form 0 (mute) to 100 (max).
  @param addHarmonic Whether to add an harmonic, one octave up. */
  public static void generateTone(int hz,int msecs, int volume, boolean addHarmonic)
    throws LineUnavailableException {
    float frequency = 44100;
    byte[] buf;
    AudioFormat af;
    if (addHarmonic) {
      buf = new byte[2];
      af = new AudioFormat(frequency,8,2,true,false);
    } else {
      buf = new byte[1];
      af = new AudioFormat(frequency,8,1,true,false);
    SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
    sdl = AudioSystem.getSourceDataLine(af);
    sdl.open(af);
    sdl.start();
    for(int i=0; i<msecs*frequency/1000; i++){
      double angle = i/(frequency/hz)*2.0*Math.PI;
      buf[0]=(byte)(Math.sin(angle)*volume);
      if(addHarmonic) {
        double angle2 = (i)/(frequency/hz)*2.0*Math.PI;
        buf[1]=(byte)(Math.sin(2*angle2)*volume*0.6);
        sdl.write(buf,0,2);
      } else {
        sdl.write(buf,0,1);
    sdl.drain();
    sdl.stop();
    sdl.close();
  public static void main(String[] args){
    Runnable r = new Runnable() {
      public void run() {
        Tone t = new Tone();
        t.setVisible(true);
    SwingUtilities.invokeLater(r);
}

JLudwig wrote:
Any reason why you call getSourceDataLine() twice? ..Oh wait, I know this one (..snaps fingers. yes) it is because I am a mor0n, and forgot the class level (static) attribute declared earlier in the source when I (re)declared the local attribute and called getSourceDatLine (which was redundant, given the next line, which as you point out also called getSourceDataLine).
There are (at least) two ways to correct this problem.
1) Remove the class level attribute and the second call.
2) Remove the local attribute as well as the first call (all on the same code line).
Method 1 makes more sense, unless you intend to refactor the code to only instantiate a single SDL for however many times the user presses (what was it? Oh yeah..) 'Generate Tone'.
My 'excuse' for my odd programming is that this was 'hacked down' from a longer program to form an SSCCE. I should have paid more attention to the fine details (and perhaps run a lint checker on it).
Thanks for pointing that out. I guess from the fact you spotted it, that you have already corrected the problem. That you thought to report it, gives me confidence that you 'will go far (and be well thought of, besides)' in the open source community.
..This is quite handy, thank you.You're welcome. Thanks for letting us know about the error (OK - the pointless redundancy). Thanks to your report, other people who see this code later, will not have to wonder what (the heck) I was thinking when I did that.
Another thing I noted, now I run the source on a 400MHz laptop (it's hard times, here) is that the logic could be improved. At the speeds that my laptop can feed data into the SDL, the sound that comes out the speakers approximates the sound of flatulence (with embedded static, as a free bonus!).
Edit 1: Changed one descriptive word so that it might get by the net-nanny.
Edited by: AndrewThompson64 on Mar 27, 2008 11:09 PM

Similar Messages

  • Any example code to generate and measure both channels using a 4451 DSA card?

    I want to generate signals and check the magnitude and phase performance between the inputs on a 4451 DSA card. It seems like there would be some example code already available for this function.

    I've attached an example which shows how to perform sychronized input and output with a NI-4451 board. This example only acquires the raw voltages and displays them on a graph. If you want magnitude and phase information, consider using a complex FFT algorithm.
    Hope this helps,
    Jack Arnold
    Application Engineer
    National Instruments
    Attachments:
    DSA_Simultaneous_IO_(reduced_ringing).vi ‏177 KB

  • How to generate a tone

    This should be a trivial question but I can't seem to find the answer!
    I want to generate a tone of a given frequency for a specified duration. For example, I want to generate a tone of 440Hz for 0.6 of a second.
    In the documents I can see on the Apple developer site, I can see how to do this if I have a whole set of .WAV files which I can then read, edit and play, but this seems to be way off the mark for what I want to do.
    In Garageband I can get a tone for as long as I press a "keyboard" key, so there must be some way to actually generate the tone but I don't seem to be able to find this information within all of the other audio capabilities.
    Thanks
    Susan

    You could always fill some audio queue buffers with the appropriate sine wave (math function sin(), or complex recursion or precalculated table lookup for much better performance). Increment each sample's phase by 2piF/Fs, and multiply the resulting sinewave by a volume level, for a duration*Fs number of samples. Remember to save the current phase between queue buffers and to maybe ramp down the level of the first and last few sinewave cycles to prevent clicks and pops.
    .

  • Setting audio tone for exporting video (-12 or 0db?)

    Hi,
    I'm exporting a production as full uncompressed video to create a data DVD which will then be used to strike copies in different formats. I have 2 Q's.
    1) I'm prepping bars & tone at the head, & I noticed that the default setting for FCP HD 4.5 is to have audio tones at -12db. I'm from the old school of audio where tone was always set to 0db. I'm guessing that the higher dynamic range of digital audio makes some arguement for the -12, but I want to be sure.
    2) Also, its a music video. I'd heard the recommendation to have program audio levels peak at -6db to keep it from having unusually loud audio, but I'm wondering if that recommendation is for narratives & based towards dialog levels? Any issues with a music video having audio levels that peak at or close to 0db?
    Thanks a lot.
    Duane

    Duane this is an example of where old school is completely trumped by new school.
    In the analog world 0 dB was the point you wanted to be near at your loudest, and MAYBE peak over very quickly at the very loudest point of your track.
    in our digital domain these days, 0dB is now the point of no return. Hit zero and your track is distortedwith no chance of saving it.
    pretend that fcp's -12 equals 0 on an analog scale, and then imagine you've got up to -6 for headroom for the loudest things. NEVER go anywhere above -6 and you'll never have a problem.

  • Error when using example code

    Hi all,
    im trying to create a program for communication over a LAN network with a spectrum analyser.
    when i use a standard example code i get errors like this one:
    [Linker error] undefined reference to `viOpenDefaultRM@4'
    did i made a fault in linking?

    DAV C++ uses a GCC based compiler. The VISA DLL is compiled with MSVC. This will cause a problem with the calling convertions used and expected.
    Basiclly the visa DLL uses 'viOpenDefaultRM' but the GCC expects viOpenDefaultRM@4, and thus can't find it in the DLL. You can solve this manually.
    The basic steps are:
    1. Generate a .def file from the DLL for example with pexports.
    2. correct the .def file so all the functions have the correct decorations as expected by GCC.
    3. Create a new import library,
    For more infomation see this post about the same issue with NI-DAQmx
    An other option would be to use the Visual Studio 2005 express editions?
    And in some configuration you will need to buy a license to use NI-VISA: http://www.ni.com/visa/license.htm
    Hope this helps
    Karsten

  • How to use PXIe-5673e to continously generate dual-tone waveform?

    Hi, everyone!
     I want to use PXIe-5673e to continously generate dual-tone waveform, and I have see some examples of RFSG, but I still don't know which one to use, can someone help me? 
    Thank you very much!!

    See if this example VI helps
    Ches this one too

  • Code to generate incremental ip address

    Hi,
    I want some help in writing a code for the following task.
    Task - given an input ip address, generate an incremental(next) ip address from the input ip address considering that the subnet mask is 255.255.255.0
    For example i have something like :
    Input IP Address Generated value should be
    1) 10.10.11.1 10.10.11.2
    2) 10.10.11.254 10.10.12.1
    3) 192.168.12.5 192.168.12.6
    4) 10.254.254.254 11.0.0.1
    5) 192.253.254.254 192.254.0.1
    code sample :-
    this code sample is not complete implementation, so i need help to write code to generate the next IP Address
    Class IpAddress is a foundation Class used, which has methods to get the IP Address in String, bytes...
    code is as follows : -
    IpAddress ipAddr = new IpAddress(new String("10.10.11.1"));
    IpAddress newIPAddr= null;
    byte []ipAddrByte = ipAddr.getAddress();
    byte []newBytes= new byte[4];
    newBytes[0]= ipAddrByte[0];
    newBytes[1]= ipAddrByte[1];
    newBytes[2]= ipAddrByte[2];
    newBytes[3]= ipAddrByte[3];
    use the input Ip Address(ipAddr) to generate the next Ip Address..
    the input IP Address will be passed to this function(module), consider the subnet mask to be 255.255.255.0(last byte has the host id).
    please help..
    regards,
    rohan

    public String incAddr(String ip)
      int i;
      int addr[] = new int[4];
      StringTokenizer st = new StringTokenizer(ip, ".");
      for (i = 0; i < addr.length; ++i)
        addr[i] = (Integer.valueOf(st.nextToken())).intValue();
      for (i = 3; i > 0; ++i)
        if (addr[i] >= 254)
          addr[i] = 0;
          ++addr[i - 1];
        else
          ++addr;
    if (addr[0] >= 254)
    System.out.println("Illegal IP Generated");
    addr[0] = addr[1] = addr[2] = addr[3] = 0;
    else
    ++addr[0];
    return addr[0] + "." + addr[1] + "." + addr[2] + "." + addr[3];
    } // incAddr
    This is UNTESTED.. but should be close... needs some saftey stuff put in.. but
    there U go.
    Might I suggest that if you could not come up with the simple logic,
    CHANGE MAJORS!

  • How can I code to play audio continuously from page to page in iBooks for reflow ePub

    Hi,
    I have tried and successfully completed the iBooks ambient soundtrack option in Fixed Layout ePub. It works fine.
    But while trying the same in Reflow ePub, it is not working in iPad iBooks. I have latest iBooks version and latest iOS version in my iPad.
    Please let me know how can I code to play audio continuously from page to page in iBooks for reflow ePub?
    Thanks,
    Sundaram

    As soon as the user turns to the next page, the audio stops.
    That's how it works in all cases.
    the book is a read aloud book.
    See the 'How-To Read Aloud' section in iBA Tips and Tricks 01

  • Question on the example code 8253eventcount.c

    Hi.
    I saw the example code 8253eventcount.c before in the NI-DAQ6.9.x. That is very useful.But i still confuse that "Do i need to set up each clock pulse duration?". From the program, it seems that the counting process solely depends on the function NIDAQDelay(sec).....
    By the way, if i am now using an old version of NI-DAQ6.8.5, How can i update some calculated voltages for each 1ms. Although i have read and followed the procedures in the user mannual of lab-pc+,but, i am still not sure how to program the counterA2 with appropriate update interval. Could anyone give me an example code? It seems that no examples are given in the version of NI-DAQ6.8.5.
    I am now using lab-pc+ with Ni-daq6.8.5 by using c++ and win
    dows95 as my working platform.Please help me in anyway! Thanks!
    Attachments:
    Lab_PC+_AO.cpp ‏2 KB

    The NIDAQDelay() is only in there to control how often the program checks the current count on the counter. If it is set to 1 seconds, it will read the counter every one second and return how many counts have been read since the start. If you take that function out, the program will check the counter as fast as it can which will tie up your CPU.
    As to your question about calculated voltages, can you be more specific as to what your application is and what you are trying to do, I'm a little confused.
    Brian

  • Acrobat 7.0 ActiveX Object example code in Lookout

    Help folks!
    I'm trying to set up the Adobe Acrobat 7.0 Browser Document ActiveX Object under Lookout 6.0 but it doesn't work. My goal is to display a pdf document by lookout.
    What should I set by Property Browser...?
    What should I set by Property Pages...?
    What should I set by Value Property:?
    What means the term "Property" in this kind of objects?
    Is there an example code I can get?
    Any suggestion will be appreciated.
    Thanx.

    I don't know of a FREE ActiveX control for MS Word.  However, if you have MS Word installed on the same computer, you can use MS Internet Explorer ActiveX Control to view Word documents. 
    But before we do that, we have to make sure that MS Word is set to open documents in the "same window."  This basically opens a DOC file in Internet Explorer itself rather than launching a new MS Word window and then opening the DOC file in it.  To set this (if it isn't already):
    1. Launch Windows Explorer. 
    2. From the Tools menu, select "Folder Options"
    3. Click the "File Types" tab. 
    4. From the listing of "Registered File Types," select "Microsoft Word Document," (you can get to it fast by typing "DOC"); click Advanced. 
    5. Click the "Browse in same window" check box -- this toggles whether a Word document is launched outside of Internet Explorer. 
    6. Click OK to close the dialog boxes. 
    NOTE:  if the DOC still opens in a new MS Word window (and not IE), go back and toggle the check-box. 
    In Lookout, use the Lookout Webbrowser control (which is nothing but MS IE Control).  Specify the file path to the DOC file as the URL.  I am attaching a process file which does this using a TextEntry object. 
    Hope this helps.
    -Khalid
    PS:  not sure when this changed but we can't directly attach .L4P files to a post.. what a pain!  Please take a minute to add your weight to this request: 
    http://forums.ni.com/ni/board/message?board.id=130​&message.id=2142
    Message Edited by Khalid on 12-28-2005 02:55 PM
    Attachments:
    doc_process.zip ‏4 KB

  • Hi I need this asap... "Java code to generate XML File from XML Schema"

    Hi all....
    I need this asap... "Java code to generate XML File from XML Schema i.e XML Schema Definition, XSD file".
    Thankz in advance...
    PS: I already posted in the afternoon... this is the second posting.

    take look at :
    http://sourceforge.net/projects/jaxme/
    this might help...

  • Java code to generate XML File from XML Schema

    Hi I need this asap... "Java code to generate XML File from XML Schema i.e XML Schema Definition, XSD file".
    Thankz in advance...

    JAXB has been available as an early release download for some time. There are also XML Binding packages available from Borland (JBuilder) and Castor. These tools create Java classes from a source document, xml,dtd etc. You can use these classes to marshal-unmarshal XML documents.
    Dave

  • Has anyone got the Comsoft Profinet example code working??

    Hello!
    I have a cRIO Profinet card and I'm attempting to get the example code working.
    I have followed the instructions in GettingStarted_cRIO_PN_IO_Device.pdf
    I have created an empty project with just the 9023 and 9113 present, and copied the 3 items from the example project cRIO PN IO-Device (LV 2012) as per the documentation.
    When I try to compile I get the error shown attached.  I cannot view the error as the VI is password protected.
    In 5 years of working with cRIO using many different c-series modules from NI and 3rd parties I have never come across a password protected example Vi - this is very disappointing!  I don't see how it will be possible to use the card without being able to access this VI, and clearly it is impossible to use it without this VI as they are unwilling to share its functionality.
    Has anyone got this working on anything other than a 9104 (which the example uses?)  Does anyone know the password?  Is it possible to use the card without using this example code?
    I will be communicating with a Siemens PLC (acquiring a load of U16s and logging on the cRIO at 20ms intervals).
    Many thanks for any input, or any experiences of using this card.
    Aaron
    LabVIEW/RT/FPGA 2012
    NI-RIO 12.0.1
    cRIO 9023 controller and 9113 chassis with COMSOFT PN module in slot 1.
    Attachments:
    PN_error.png ‏44 KB
    PN_error2.png ‏20 KB

    Just for the record, I am using the CRIO-PN with cRIO-9081 and cRIO-9068 integrated chassis successfully.
    LabVIEW (RT/FPGA) 2013 SP1.
    I didn't use the higher level ComSoft example code directly, as the VIs use so many control/indicators that the FPGA usage is sky high. I rewrote them to pass the I/O data via DMA FIFOs.

  • What audio tones could I expect to hear on BT land...

    Subject says it all really. But in the interests of clarity: I subscribe to no caller id, caller waiting or other such services but more and more often my phone calls are interrupted by pairs of identical audio tones approx. 0.5 seconds apart and repeated at, perhaps, 20 or 30s intervals. Not having a frequency meter I can't determine the actual tone frequency but it is a low to medium frequency rather than high - not a whistle. The other party's voice is cut when the tone is present but they cannot hear the tone. The common factor is my line - not who I am speaking to. And I can't remember if it occurs only when I have initiated the call. TIA Richard

    bfg wrote:
    Hi Strugglin,
    I would want to rule out my phones from causing the noise (is it like the dialling tones for a particular number?) i.e ayour phone dialling a number during the call.
    Erm, thanks for your reply Bfg.  I had hoped that my description was adequate.  The noises - sounds really - are pairs of mid frequency tones separated by about 0.5s repeated at about 20 or 30s intervals.  They are what I would expect to hear if I had call waiting or BT Answercall or any other 'add ons'.  They are not unlike the call waiting signal on a mobile telephone.  They are not the sound of pulse or tone dialling superimposed on a voice call.
    I'm not sure that I can bear the thought of logging a fault with BT.

  • Is there example code for using Ni488 and PCI-GPIB card in non controller mode?

    Is there example code for using Ni488 and PCI-GPIB card in non controller mode?

    cymrieg,
    Your code looks good to me. What is the problem? What happens when it fails? What is the IBSTA value on the controller, and at what point in the code does it stop? What is the IBSTA value on the slave, and at what point does it stop?
    One thing is that you might not want to call IBCLR() in a loop on the device. At the beginning of the program is fine...This will send a clear command to the device and will clear out any LACS and TACS bits that might be set. Also your IBDEV call shouldn't be in a loop.
    Hope this helps, but let me know if you need more information.
    Scott B.
    GPIB Software
    National Instruments

Maybe you are looking for

  • Did you know that your iPhone will burn up your USB ports?

    I have two Power Macs, Power PC G4s. After backing up my phone on both of these computers, the USB port does not work. What's up with that and how do I get the port to become usable again?

  • 10.5.3 - Erratic Airport connection since update on Mac Mini G4

    Updated to 10.5.3 a couple of days ago. First it took ages to install and the system stalled on "writing installing script". Had to take a deep breath and restart. All was fine with wireless until yesterday when all of a sudden it stopped working. Ai

  • How to get samsung display

    i first had samsung display,ants got into the display.Got the screen replaced but they gave me lg. So talked to customer care got it replaced again but they gave me new lg screen. Both the lg panels have yellow tint and very low brightness. How do i

  • HR:Anual PF Report

    Hi, While running the annual PF report(PC00_M40_PFY ) for an employee we are getting 2 PF numbers which happed due to wrong uploading.Hence in the form 3A printout the values are flowing in two pages with respect to the two PF numbers.i want these va

  • How to create a button Widget

    Hi, Can any one tell me how to create a button widget, I've created one & it can be seen in my plugin, but it doesn't work, in .fr file i created the widget as, ButtonWidget            kEXTCODGoButtonWidgetID,                  kSysButtonPMRsrcId,