Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Example: Code to generate audio tone

User_64CKJDec 5 2007 — edited Mar 17 2009
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);
  }
}

Comments

Billy Verreynne

Use a calculation in the SQL projection as the column value to use as colour. Fully flexible as you determine the colour (or colours) to use as part of the output for that specific row from the SQL cursor.
Hide this column in the interactive report. No reason to have it viewable by user.
For the relevant column to colour code, use the the colour column to set the CSS class to use to style and colour that column value.
E.g. the SQL column COLOR_CODE is use for colouring column NAME:
image.png
As for wasting your time on this - perhaps basic ignorance of how to use CSS classes in HTML DOM element rendering is the problem. Not APEX so-called lack of documentation and examples.

user7911366

Did you not read or understand the problem? What about wasting time, if I have to become an expert in HTML, CSS, Javascript etc just to do something as trivial as setting colors, yes I am wasting my time looking for undocumented information. In no APEX manual is there clear information about the properties mentioned. If you don't want to help, please don't give rude answers...
And by the way, your solution doesn't work as demonstrated in the examples I've shown.

Billy Verreynne

My example works very well in all APEX versions since v5. May also have worked in prior versions. Try it.
You obviously seem unaware of https://apex.oracle.com/pls/apex/apex_pm/r/ut/design-overview.
Your approach fails because you do not seem to understand the basics of HTML5 and CSS3 - why inject a TD element into the report table? Use a SPAN element as shown.
Do not manually code style via the STYLE attribute of an element. It is horribly inflexible and unmaintainable. Use the CLASS attribute to assign the classes to use for styling that element.
Where possible use APEX Universal Theme classes as shown in https://apex.oracle.com/pls/apex/apex_pm/r/ut/color-and-status-modifiers and https://apex.oracle.com/pls/apex/apex_pm/r/ut/layout-modifiers and https://apex.oracle.com/pls/apex/apex_pm/r/ut/content-modifiers.
Stick to the basics that is provided instead of steamrolling ahead with what you perceive should work.

TexasApexDeveloper

Wow, Billy I guess user7911366 doesn't know how to at least say THANK YOU for an assist.. Ever heard of he fact ths is a FREE support forum? If you keep this up, not too many people will flocking to help you in the future..

Thank you,
Tony Miller
White Rock, NM

user7911366

Oh, I'm sorry if I hurt your feelings towards Billy, but the point is that I didn't ask for an assessment of my knowledge but help with something I obviously don't know, after all this is a forum to resolve doubts and not to chat or show its supposed superiority. If the answer had only solved the problem despite the unnecessary rudeness, as well as yours, of course I would have appreciated it. If you are not going to help please don't be posting useless nonsense. Have a nice end to the day.

user7911366

"My example works very well in all APEX versions since v5. May also have worked in prior versions. Try it."
image.pngimage.pngimage.pngSorry, as I said before, your example doesn't works.
"Your approach fails because you do not seem to understand the basics of HTML5 and CSS3 - why inject a TD element into the report table? Use a SPAN element as shown."
The desired result is to color the cell and not just the content, the test with the td tag was to show the effect I got in my tests and not to say that this is the correct solution.
Thanks for the links but there is no solution there.

Billy Verreynne

You need to style the class via CSS.
Here is an example. Report query with:
image.png
The HTML expression for column OBJECT_NAME:
image.pngAnd the HTML expression for column STATUS:
image.png
2 new CSS classes are introduced - type-table and type-index. The style is added to the page attribute CSS Inline:
image.pngThe report looks as follows:
image.png
Unfortunately there are no means as far as I know in CSS to style the parent element of the span element with class type-table for example. Thus you cannot colour code the parent TD element via CSS.
You can however use a JQuery selector - select all type-table class elements with a TD parent element, and style the TD element. Example code added to page attribute:
image.png
This now colour codes the TD element only when the page loads - you also need to do the same when the report region dynamically changes via sorting, filter, and other changes. This will need to be done via a dynamic Javascript action fired after the report refresh event.
Report looks as follows with using the JQuery selector to colour code the TD elements:
image.png

user7911366

Thanks again for your example but it doesn't meet the requirements. Please read my post again, what I need is to dynamically define the fore and background colors of a cell using the colors recorded in the BCOLOR and FCOLOR columns in the same record. These colors can be changed by the user, who can also include and exclude records. The region has to be base table because it will be automatically generated by APEX after executing the creation script.
Therefore, any solution that uses a query with CASE, DECODE, etc. will not meet the need because the definitions will be typed HARD CODE inside the query, which can never contain all the possible color combinations that the user wants to configure.
The solution must exist but it is clear that it is not a question of basic knowledge of CSS, HTML or JavaScript. The Highlights functionality itself does something similar, but I haven't found a way to configure it to do this dynamically using the colors of the current record. If the colors change or new records with new colors are inserted the Highlights will fail.
In fact, if you look closely at the open console in my example, you'll notice that the td tag I created works but APEX creates another one or modifies the original one leaving no configuration, creating a phantom column that shifts everything to the right.
If a simple problem doesn't have a simple solution then the product has failed!
If simple information cannot be found quickly then the product has failed!
Someone at Oracle hasn't done their homework...

Billy Verreynne

what I need is to dynamically define the fore and background colors of a cell using the colors recorded in the BCOLOR and FCOLOR columns in the same record.
Where does the actual BCOLOR and FCOLOR values come from? Will each cell (column value in a row) have its own unique FCOLOR and BCOLOR value?
These colors can be changed by the user, who can also include and exclude records.
How? Where does the user input of colours come from? How does the user define the condition(s) to evaluate the row and/or column to determine what colours to use?
Therefore, any solution that uses a query with CASE, DECODE, etc. will not meet the need because the definitions will be typed HARD CODE inside the query, which can never contain all the possible color combinations that the user wants to configure.
Disagree. SQL projection is an ideal mechanism in APEX to evaluate user supplied predicates to evaluate and determine rendering classes (or manual styles) to apply.
In fact, if you look closely at the open console in my example, you'll notice that the td tag I created works but APEX creates another one or modifies the original one leaving no configuration, creating a phantom column that shifts everything to the right.
Exactly. You very rudely are disrupting the defined HTML TABLE element structure by inject a new column (TD element) into the table body, without also providing a column header in the table header for that new column.
And this clearly points to a lack of basic understanding of HTML.
If a simple problem doesn't have a simple solution then the product has failed! If simple information cannot be found quickly then the product has failed!
A ridiculous statement. The problem statement does not determine the simplicity of the solution. Else we would have solved the simplistic problem statement of containing nuclear fusion with magnetic fields - enabling us to provide unlimited energy via nuclear fusion to mankind.
Someone at Oracle hasn't done their homework...
You have two basic choices. Whine and complain while wallowing in ignorance. Or take this as a learning opportunity to gain experience and skills that will make you a better software developer.
And getting frustrated and upset will not solve your problem.
I like technical problems. I love taking them apart, figuring out the internal working components, isolate the issue, and trying to fix it. I'm keen to help you solve your problem.
But getting upset at Oracle, APEX, me and whatever else, do not detail the actual problem you are trying to solve. How about giving us the business requirement that you are trying to address with this user-can-dynamically-and-magically-colour-code report columns solution?

TexasApexDeveloper

Billy, chalk this one off to a spoiled little man who has no idea how ask for help. He will continue to whine and stomp his feet as apposed to ACTUALLY trying your solution. Again, since I have been here in the forums a few years, and have seen a few people like this show up. They either will change their tune or not asking for help up here..

I for on thank you for at least TRYING to show this user the answer.. If they cant be bothered to at least try what you have suggested that is their problem, NOT yours.

Thank you,

Tony Miller
White Rock, NM

user7911366

Once upon a time there were a couple of idiots who think of themselves as the Harry Porter Javascript Jedis whose baby can't do something that simple and get annoyed and frustrated at anyone who tells them that. kkkkkkkkkkk

Billy Verreynne

Once upon a time there were a couple of idiots who think of themselves as the Harry Porter Javascript Jedis whose baby can't do something that simple and get annoyed and frustrated at anyone who tells them that. kkkkkkkkkkk
Meh.
How about explaining the business requirement behind your problem?
Understanding the actual requirement provides far more insight than presenting a problem solution that does not work, and asking for assistance with what possibly is a flawed solution.

TexasApexDeveloper

User7911366, why dont you at least change your profile to have your name, or is that task even beyond your comprehension? We are friendly group here and do not bite (unless bitten first).
I will also ask again, you do know this is a FREE support site. People here are GIVING away their time and knowledge, you MIGHT want to be a little more appreciative and a little less child-like, if that is not asking too much.
And I in NO WAY think I am a Harry Potter JavaScript Jedi (What a strange combination of Harry Potter and Start Wars) What I am is an experienced Oracle Apex developer who has been here in the forums for a few years. Show some respect to those who have been here a while and MIGHT know more than you do.. When someone offers help out of their busy day, you should be polite and maybe thank them?
Thank you,

Tony Miller
White Rock, NM

user7911366

Hey HPJJs, are you the forum owners? No, obviously not. So go suck your socks and stop pretending to be a smartass, you couldn't even understand the problem, you copied part of my example to present as your solution and to make it even worse complicated it unnecessarily to reach the same result.
There are thousands of unanswered posts, look for one where you can present the correct solution. You will probably feel happy in the beginners' questions section.

TexasApexDeveloper

I would HIGHLY recommend that you change your attitude before it is reported to the forum admin's.. Try to act like an adult..
'nuff said..

user7911366
Answer

Okay HPJJ, you got me really scared this time. I promise to try to be as grown up as you are and also learn your tricks of copying others' ideas and presenting them in a fancy way to look original.
Thank you very much for the tips !

Marked as Answer by user7911366 · Jun 18 2021
1 - 16
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Apr 14 2009
Added on Dec 5 2007
11 comments
14,334 views