 |
 |
Index ‹ java-programmer
|
- Previous
- 1
- Leaf linked binary treeHi,
I need a LeafLinked Binary Tree for one of my current projejcts but I
can't find any. Does somebody know a good and performant implementation
I could use or do I have to code it myself?
Thanks,
Snyke
- 1
- Best site for javahttp://javamobileweb.cogia.net
interactive site for java , mobile , wap and web .
a very helpful team also for all your question and problem
- 5
- It don't work with "PBEWithHmacSHA1AndDESede". What wrong?Hi.
In the following source, I got the exception :
"java.security.NoSuchAlgorithmException:
Cannot find any provider supporting PBEWithHmacSHA1AndDESede"
<source>
Cipher cipher;
SecretKey secretKey;
PBEParameterSpec parameterSpec;
try {
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
cipher = Cipher.getInstance("PBEWithHmacSHA1AndDESede");
SecretKeyFactory secKeyFac = SecretKeyFactory
.getInstance("PBEWithMD5AndDES");
secretKey = secKeyFac.generateSecret(keySpec);
parameterSpec = new PBEParameterSpec(salt, iteration);
} catch (NoSuchAlgorithmException e) {
} catch (NoSuchPaddingException e) {
} catch (InvalidKeySpecException e) {
}
</source>
The source above work with "PBEWithMD5AndDES". But, not
with "PBEWithHmacSHA1AndDESede". In the Sun's JCE API
Reference Guide, the "PBEWithHmacSHA1AndDESede" is the
standard name ( I use JDK 1.5 RC ).
What wrong? Thank you for your help.
- 5
- ""SEE THE BEST FRIENDS FOR YOUR SEX TALK""""SEE THE BEST FRIENDS FOR YOUR SEX TALK""
SEX TALK+SEX_JAFKJAJ;=SEXWORK
*********************************
http://www.freewebs.com/sociwok/
********************************
http://amigos.com/go/g903136-pmem
- 5
- How to ignore invalid SSL CertificatesHi everybody :-)
I'm trying to build an application that serves as a Client Side
frontend for a webpage using HttpClient 2. Because I have some security
problems I decided that using https would be nice, but my SSL
certificates continue to fail validation and I'm wondering wether it is
possible to let HttpClient ignore Certification Failures? And if yes,
could you please give me a working example?
Greets,
- 5
- Making the most of codeI have a web site that uses JSP and some back end classes to manage
data in a MySQL database. It does okay and has run well for about 3
years. It has, however, grown to the point where I need to redesign
some of it to be more dynamic. I've recently started incorporating
Hibernate and JavaServer Faces to ease the development now and make it
easier for me to make changes later on. Or at least that was my plan.
Each database table maps to a Java class. I will easily have 25-30
tables before I am done. I am okay with 25-30 classes to represent
the data, but my concern is when it comes to the associated classes
needed to manage the data connections and such. I find that I am
cutting and pasting way too much similar code into these separate
classes.
For example.
I have a HibernateDAO class that manages the Hibernate session.
Each class then has its own DAO class that extends the HibernateDAO
class and the code within the extended DAO classes is virtually
identical.
Here is one method from my clientDAO class.
public Client add( Client client) {
try {
begin();
getSession().save(client);
commit();
return get(client.getClientId()); //not every class
will have a clientId member
} catch (HibernateException e) {
rollback();
System.out.println( "Could not add client: " +
client.getClientId() + " : " + e); //message hard coded for client
class
return new Client();
}
}
And then in my ContactDAO class I have this.
public Contact add(Contact contact) {
try {
begin();
getSession().save(contact);
commit();
return get(contact.getId()); //not every class will have
an Id member
} catch (HibernateException e) {
rollback();
System.out.println( "Could not add contact: " +
contact.getId() + " : " + e); //Message hard-coded for contact class
return new Contact();
}
}
Note that the code is virtually identical.
The begin(), getSession(), rollback(), and commit() methods are all
from the HibernateDAO superclass.
I tried using Generics to make the return type and parameter <T>, but
this only gets me so far. I cannot declare a new instance of <T>, or
at least I don't know how to. And the method uses values that are
specific to the class in question. I.E. not every data class will
have a getId() method.
I am not sure if any of that made sense, but the crux of the issue is
I am trying to avoid cutting and pasting code and then having to
remember to update it in 25 different places when I make a change. I
feel like there is a way to do what I want, but I just don't have the
experience to see it.
If anyone can point me toward some documentation that might help set
me straight, I would appreciate it.
Thanks.
- 6
- 10
- HP Desktop for sale!Hi,
I have an unused HP Pavilion with the fallowing specs:
# Processor: AMD Athlon 64 X2 4000+ (2.1GHz, 2000MT/s System Bus)
# Memory: 2048MB PC2-5300 DDR2 SDRAM memory (2x1GB) (expandable to 8 GB (4 x 2 GB) (64-bit OS)/ 4 GB (4 x 1 GB) (32-bit OS))
# Hard Drive:320GB 7200RPM SATA 3G (3.0 Gb/sec) hard drive
# Optical Drive: 16X DVD(+/-)R/RW 12X RAM (+/-)R DL LightScribe SATA drive
# Expandable Drive Bay: HP Pocket Media Drive bay
# Video Graphics: Integrated graphics
# Network Interface: Integrated 10/100BaseT network interface
# Sound: High Definition 8-channel audio
# Fax/Modem: 56K bps data/fax modem
# Operating System: Genuine Windows Vista?Home Premium
This is "used" but basically brand new (it has literally been on for no more than 6 total hours..) is only 1 month old..
PRICE: $425 OBO
Email- email***@***.com
- 12
- Is heavy client dead? Is swing applet dead?Today most Java UI developers are focusing on solutions like Struts,
Taperstry, and JSF. It seems that noone care about Swing applet as a
choice as rich client.
Is heavy client dead? I think heavy client solution like swing applet
is still good for business application. Especially for many internal
business projects. In internal business environment, the download speed
is usually not a problem. Swing also provides better GUI than html.
Swing has the ability to cache information on the client side which
save a lot of network calls to server.
Do you agree? Should we all forget about Swing and heavy client
solution, and vote for Struts and JSF?
Thank you
Jim
- 12
- read from file in jspI'm develloping a site based on jsp.
In my javacode I want to read from a file located in the document root
of the web application. How do I do this when I dont know the name of
the host.
Should I consider locating the file somewhere else. It should actually
only be accessible from the code of the application.
Thanks for your help.
Nikolaj
- 14
- which data structure best fits this?hi,
i am looking for a data structure for fast retrievals... and here is my
scenario.
this table is about foreigncy exchange. i will have a buy currency,
sellcurrency, levels, and rate.
A transaction involves from a BUY currency to Sell currency, and it can
have multiple levels, meaning... if the sell amount is 1000, the rate
is 1.1, but if the sell amount is 2000, the rate is 1.2..etc...
Say there is a fixed amount of currencies that I need to maintain (say
10 type only) And I need to store all these rates in a structure, for
fast retrieval..
More concrete example.
Sell : USD Buy: EUR Level: 1 - 1000 rate: 1.1
Sell : USD Buy: EUR Level: 1000 - 5000 rate: 1.2
Sell : USD Buy: EUR Level: 5000 - 99999999 rate: 1.3
Sell : USD Buy: CAD Level: 1 - 1000 rate: 1.1
Sell : USD Buy: CAD Level: 1000 - 5000 rate: 1.2
Sell : USD Buy: CAD Level: 5000 - 99999999 rate: 1.3
Sell : USD Buy: GBP Level: 1 - 1000 rate: 1.1
Sell : USD Buy: GBP Level: 1000 - 5000 rate: 1.2
Sell : USD Buy: GBP Level: 5000 - 99999999 rate: 1.3
------ So, Sell for USD type is finished here.
Sell : EUR Buy: USD Level: 1 - 1000 rate: 1.1
Sell : EUR Buy: USD Level: 1000 - 5000 rate: 1.2
Sell : EUR Buy: USD Level: 5000 - 99999999 rate: 1.3
Sell : EUR Buy: CAD Level: 1 - 1000 rate: 1.1
Sell : EUR Buy: CAD Level: 1000 - 5000 rate: 1.2
Sell : EUR Buy: CAD Level: 5000 - 99999999 rate: 1.3
Sell : EUR Buy: GBP Level: 1 - 1000 rate: 1.1
Sell : EUR Buy: GBP Level: 1000 - 5000 rate: 1.2
Sell : EUR Buy: GBP Level: 5000 - 99999999 rate: 1.3
------ Sell for EUR is finished here.
so on with GBP, and CAD.
my requirements:
Say, someone tell me, what are all the rates for all the levels and
BuyType from EUR as sell?
Then that means I have to send back all the EUR as sell type.
Or, if someone say, what are all the rates for all the buytype for USD
from EUR as sell?
Then that means i have to send back all the EUR as sell, and USD for
Buy.
Or, if someone say, what are all the rates for all the buytype as GBP?
Then, i will have to send back all the buytype as GBP (including all
levels)
Or someone can just ask for a specific level as well for any buy type
of sell type, or both.
I was thinking about hash of hash... but if i have the Sell type as key
of the outer hash... then the inner hash will need to have a buytype as
the key... but then, i will have multiple levels...if i put the
multiple levels in an array of an object, and this object as the value
of this inner hash, that should be fine... but i am worry about the
speed.
Ideas?
thanks,
T
- 14
- 16
- Array Error
I'm getting two errrors with the simple code below:
For line 5 I get " <identifier> expected "
For line 6 I get " ']' expected" and also " <identifier> expected "
What gives?
Thanks
------------------------------------------
1 package com.dlm.testing;
2 import java.util.Arrays;
3 public class Test1 {
4 public String[] names;
5 names = new String[50];
6 names[0]="Jones";
7 }
- 16
- Java installationTry to install Java on my computer, but Microsoft tells me:
THE JAVA RUNTIME ENVIRONEMENT CANNOT BE LOADED FROM <bin\hotspot\jvm.dll
What am I doing wrong to install that applet
please reactions
Robert
- 16
- IDE and good bookHi,
What is the best IDE for Java development:
1)eclipse 3.1
2)sun 1
3)jbuilder
4)gui's are for wusses use vi and a command line ant
What is a good book to learn java 1.4?
What is a good book to learn swing?
thanks in advance
|
| Author |
Message |
garskof

|
Posted: 2006-2-14 22:46:00 |
Top |
java-programmer, Java Sound
I am intersted in building an applet that can both play and record
sound files. I would like this to work on the widest range of platforms
(MAC, Linux, WinXP, WinNT, etc) and browsers. What would be the best
file format for the sound files to accomplish this? Would it be MP3,
WAV, or what? I am looking to have this work without any added packages
over and above JDK 1.4.x.
Thanks for any and all info.
|
| |
|
| |
 |
krisg_mcd

|
Posted: 2003-9-5 2:21:00 |
Top |
java-programmer >> Java Sound
Java Sound doesn't use any temperary files to buffer the audio. It
actually buffers the audio in the memorey. So the more recording you
do the more memorey it takes and at some point you will run out of
memorey and the application will fails.
Hope this answers your question.
-kris
"gg" <email***@***.com> wrote in message news:<baS2b.59448$K44.685@edtnps84>...
> I was trying to learn java sound and downloaded the Java Sound Demo from
> Sun. The recording part of it part seems to fail to produce the stream for
> playback when the recording length exceed about half an hour to 3/4 hr.
> I tried examineing the code to find the cause of it ( I though it could be
> fouled up by graphing) or something with the stream for too long and
> consumed too much RAM..
>
> I look for documentation whether the sound api automatically create
> temporary file to buffer the stream and failed.
>
> Can someone point me the documentation showing how to oevercome the stream
> length problem length?
>
>
> the code for the recording and playback is as follows:
> /*
> * @(#)CapturePlayback.java 1.11 99/12/03
> *
> * Copyright (c) 1999 Sun Microsystems, Inc. All Rights Reserved.
> *
> * Sun grants you ("Licensee") a non-exclusive, royalty free, license to
> use,
> * modify and redistribute this software in source and binary code form,
> * provided that i) this copyright notice and license appear on all copies
> of
> * the software; and ii) Licensee does not utilize the software in a manner
> * which is disparaging to Sun.
> *
> * This software is provided "AS IS," without a warranty of any kind. ALL
> * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
> ANY
> * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
> * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
> * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
> MODIFYING
> * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR
> ITS
> * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
> * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
> * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE
> OF
> * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
> * POSSIBILITY OF SUCH DAMAGES.
> *
> * This software is not designed or intended for use in on-line control of
> * aircraft, air traffic, aircraft navigation or aircraft communications; or
> in
> * the design, construction, operation or maintenance of any nuclear
> * facility. Licensee represents and warrants that it will not use or
> * redistribute the Software for such purposes.
> */
>
>
> import java.awt.*;
> import java.awt.event.*;
> import java.awt.geom.Line2D;
> import javax.swing.*;
> import javax.swing.event.*;
> import javax.swing.border.*;
> import java.util.Vector;
> import java.util.Enumeration;
> import java.io.*;
> import javax.sound.sampled.*;
> import java.awt.font.*;
> import java.text.*;
>
>
>
>
> /**
> * Capture/Playback sample. Record audio in different formats
> * and then playback the recorded audio. The captured audio can
> * be saved either as a WAVE, AU or AIFF. Or load an audio file
> * for streaming playback.
> *
> * @version @(#)CapturePlayback.java 1.11 99/12/03
> * @author Brian Lichtenwalter
> */
> public class CapturePlayback extends JPanel implements ActionListener,
> ControlContext {
>
> final int bufSize = 16384;
>
> FormatControls formatControls = new FormatControls();
> Capture capture = new Capture();
> Playback playback = new Playback();
>
> AudioInputStream audioInputStream;
> SamplingGraph samplingGraph;
>
> JButton playB, captB, pausB, loadB, newB;
> JButton auB, aiffB, waveB;
> JTextField textField;
>
> String fileName = "untitled";
> String errStr;
> double duration, seconds;
> File file;
> Vector lines = new Vector();
>
>
>
> public CapturePlayback() {
> setLayout(new BorderLayout());
> EmptyBorder eb = new EmptyBorder(5,5,5,5);
> SoftBevelBorder sbb = new SoftBevelBorder(SoftBevelBorder.LOWERED);
> setBorder(new EmptyBorder(5,5,5,5));
>
> JPanel p1 = new JPanel();
> p1.setLayout(new BoxLayout(p1, BoxLayout.X_AXIS));
> p1.add(formatControls);
>
> JPanel p2 = new JPanel();
> p2.setBorder(sbb);
> p2.setLayout(new BoxLayout(p2, BoxLayout.Y_AXIS));
>
> JPanel buttonsPanel = new JPanel();
> buttonsPanel.setBorder(new EmptyBorder(10,0,5,0));
> playB = addButton("Play", buttonsPanel, false);
> captB = addButton("Record", buttonsPanel, true);
> pausB = addButton("Pause", buttonsPanel, false);
> loadB = addButton("Load...", buttonsPanel, true);
> newB = addButton("New", buttonsPanel, true);
> p2.add(buttonsPanel);
>
> JPanel samplingPanel = new JPanel(new BorderLayout());
> eb = new EmptyBorder(10,20,20,20);
> samplingPanel.setBorder(new CompoundBorder(eb, sbb));
> samplingPanel.add(samplingGraph = new SamplingGraph());
> p2.add(samplingPanel);
>
> JPanel savePanel = new JPanel();
> savePanel.setLayout(new BoxLayout(savePanel, BoxLayout.Y_AXIS));
>
> JPanel saveTFpanel = new JPanel();
> saveTFpanel.add(new JLabel("File to save: "));
> saveTFpanel.add(textField = new JTextField(fileName));
> textField.setPreferredSize(new Dimension(140,25));
> savePanel.add(saveTFpanel);
>
> JPanel saveBpanel = new JPanel();
> auB = addButton("Save AU", saveBpanel, false);
> aiffB = addButton("Save AIFF", saveBpanel, false);
> waveB = addButton("Save WAVE", saveBpanel, false);
> savePanel.add(saveBpanel);
>
> p2.add(savePanel);
>
> p1.add(p2);
> add(p1);
> }
>
>
> public void open() { }
>
>
> public void close() {
> if (playback.thread != null) {
> playB.doClick(0);
> }
> if (capture.thread != null) {
> captB.doClick(0);
> }
> }
>
>
> private JButton addButton(String name, JPanel p, boolean state) {
> JButton b = new JButton(name);
> b.addActionListener(this);
> b.setEnabled(state);
> p.add(b);
> return b;
> }
>
>
> public void actionPerformed(ActionEvent e) {
> Object obj = e.getSource();
> if (obj.equals(auB)) {
> saveToFile(textField.getText().trim(), AudioFileFormat.Type.AU);
> } else if (obj.equals(aiffB)) {
> saveToFile(textField.getText().trim(),
> AudioFileFormat.Type.AIFF);
> } else if (obj.equals(waveB)) {
> saveToFile(textField.getText().trim(),
> AudioFileFormat.Type.WAVE);
> } else if (obj.equals(playB)) {
> if (playB.getText().startsWith("Play")) {
> playback.start();
> samplingGraph.start();
> captB.setEnabled(false);
> pausB.setEnabled(true);
> playB.setText("Stop");
> } else {
> playback.stop();
> samplingGraph.stop();
> captB.setEnabled(true);
> pausB.setEnabled(false);
> playB.setText("Play");
> }
> } else if (obj.equals(captB)) {
> if (captB.getText().startsWith("Record")) {
> file = null;
> capture.start();
> fileName = "untitled";
> samplingGraph.start();
> loadB.setEnabled(false);
> playB.setEnabled(false);
> pausB.setEnabled(true);
> auB.setEnabled(false);
> aiffB.setEnabled(false);
> waveB.setEnabled(false);
> captB.setText("Stop");
> } else {
> lines.removeAllElements();
> capture.stop();
> samplingGraph.stop();
> loadB.setEnabled(true);
> playB.setEnabled(true);
> pausB.setEnabled(false);
> auB.setEnabled(true);
> aiffB.setEnabled(true);
> waveB.setEnabled(true);
> captB.setText("Record");
> }
> } else if (obj.equals(pausB)) {
> if (pausB.getText().startsWith("Pause")) {
> if (capture.thread != null) {
> capture.line.stop();
> } else {
> if (playback.thread != null) {
> playback.line.stop();
> }
> }
> pausB.setText("Resume");
> } else {
> if (capture.thread != null) {
> capture.line.start();
> } else {
> if (playback.thread != null) {
> playback.line.start();
> }
> }
> pausB.setText("Pause");
> }
> } else if (obj.equals(loadB)) {
> try {
> File file = new File(System.getProperty("user.dir"));
> JFileChooser fc = new JFileChooser(file);
> fc.setFileFilter(new javax.swing.filechooser.FileFilter () {
> public boolean accept(File f) {
> if (f.isDirectory()) {
> return true;
> }
> String name = f.getName();
> if (name.endsWith(".au") || name.endsWith(".wav") ||
> name.endsWith(".aiff") || name.endsWith(".aif")) {
> return true;
> }
> return false;
> }
> public String getDescription() {
> return ".au, .wav, .aif";
> }
> });
>
> if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
> {
> createAudioInputStream(fc.getSelectedFile(), true);
> }
> } catch (SecurityException ex) {
> JavaSound.showInfoDialog();
> ex.printStackTrace();
> } catch (Exception ex) {
> ex.printStackTrace();
> }
>
> } else if (obj.equals(newB)) // 20030823 GG added this this else if
> clause to deal with not having to close to satrt new recording
> if (captB.getText().startsWith("Record")) {
> file = null;
> capture.start();
> fileName = "untitled";
> samplingGraph.start();
>
> captB.setText("Stop");
> } else {
> lines.removeAllElements();
> capture.stop();
> samplingGraph.stop();
> }
>
> loadB.setEnabled(false);
> playB.setEnabled(false);
> pausB.setEnabled(true);
> auB.setEnabled(false);
> aiffB.setEnabled(false);
> waveB.setEnabled(false);
> }
> }
>
>
> public void createAudioInputStream(File file, boolean updateComponents)
> {
> if (file != null && file.isFile()) {
> try {
> this.file = file;
> errStr = null;
> audioInputStream = AudioSystem.getAudioInputStream(file);
> playB.setEnabled(true);
> fileName = file.getName();
> long milliseconds =
> (long)((audioInputStream.getFrameLength() * 1000) /
> audioInputStream.getFormat().getFrameRate());
> duration = milliseconds / 1000.0;
> auB.setEnabled(true);
> aiffB.setEnabled(true);
> waveB.setEnabled(true);
> if (updateComponents) {
> formatControls.setFormat(audioInputStream.getFormat());
> samplingGraph.createWaveForm(null);
> }
> } catch (Exception ex) {
> reportStatus(ex.toString());
> }
> } else {
> reportStatus("Audio file required.");
> }
> }
>
>
> public void saveToFile(String name, AudioFileFormat.Type fileType) {
>
> if (audioInputStream == null) {
> reportStatus("No loaded audio to save");
> return;
> } else if (file != null) {
> createAudioInputStream(file, false);
> }
>
> // reset to the beginnning of the captured data
> try {
> audioInputStream.reset();
> } catch (Exception e) {
> reportStatus("Unable to reset stream " + e);
> return;
> }
>
> File file = new File(fileName = name);
> try {
> if (AudioSystem.write(audioInputStream, fileType, file) == -1) {
> throw new IOException("Problems writing to file");
> }
> } catch (Exception ex) { reportStatus(ex.toString()); }
> samplingGraph.repaint();
> }
>
>
> private void reportStatus(String msg) {
> if ((errStr = msg) != null) {
> System.out.println(errStr);
> samplingGraph.repaint();
> }
> }
>
>
> /**
> * Write data to the OutputChannel.
> */
> public class Playback implements Runnable {
>
> SourceDataLine line;
> Thread thread;
>
> public void start() {
> errStr = null;
> thread = new Thread(this);
> thread.setName("Playback");
> thread.start();
> }
>
> public void stop() {
> thread = null;
> }
>
> private void shutDown(String message) {
> if ((errStr = message) != null) {
> System.err.println(errStr);
> samplingGraph.repaint();
> }
> if (thread != null) {
> thread = null;
> samplingGraph.stop();
> captB.setEnabled(true);
> pausB.setEnabled(false);
> playB.setText("Play");
> }
> }
>
> public void run() {
>
> // reload the file if loaded by file
> if (file != null) {
> createAudioInputStream(file, false);
> }
>
> // make sure we have something to play
> if (audioInputStream == null) {
> shutDown("No loaded audio to play back");
> return;
> }
> // reset to the beginnning of the stream
> try {
> audioInputStream.reset();
> } catch (Exception e) {
> shutDown("Unable to reset the stream\n" + e);
> return;
> }
>
> // get an AudioInputStream of the desired format for playback
> AudioFormat format = formatControls.getFormat();
> AudioInputStream playbackInputStream =
> AudioSystem.getAudioInputStream(format, audioInputStream);
>
> if (playbackInputStream == null) {
> shutDown("Unable to convert stream of format " +
> audioInputStream + " to format " + format);
> return;
> }
>
> // define the required attributes for our line,
> // and make sure a compatible line is supported.
>
> DataLine.Info info = new DataLine.Info(SourceDataLine.class,
> format);
> if (!AudioSystem.isLineSupported(info)) {
> shutDown("Line matching " + info + " not supported.");
> return;
> }
>
> // get and open the source data line for playback.
>
> try {
> line = (SourceDataLine) AudioSystem.getLine(info);
> line.open(format, bufSize);
> } catch (LineUnavailableException ex) {
> shutDown("Unable to open the line: " + ex);
> return;
> }
>
> // play back the captured audio data
>
> int frameSizeInBytes = format.getFrameSize();
> int bufferLengthInFrames = line.getBufferSize() / 8;
> int bufferLengthInBytes = bufferLengthInFrames *
> frameSizeInBytes;
> byte[] data = new byte[bufferLengthInBytes];
> int numBytesRead = 0;
>
> // start the source data line
> line.start();
>
> while (thread != null) {
> try {
> if ((numBytesRead = playbackInputStream.read(data))
> == -1) {
> break;
> }
> int numBytesRemaining = numBytesRead;
> while (numBytesRemaining > 0 ) {
> numBytesRemaining -= line.write(data, 0,
> numBytesRemaining);
> }
> } catch (Exception e) {
> shutDown("Error during playback: " + e);
> break;
> }
> }
> // we reached the end of the stream. let the data play out,
> then
> // stop and close the line.
> if (thread != null) {
> line.drain();
> }
> line.stop();
> line.close();
> line = null;
> shutDown(null);
> }
> } // End class Playback
>
>
> /**
> * Reads data from the input channel and writes to the output stream
> */
> class Capture implements Runnable {
>
> TargetDataLine line;
> Thread thread;
>
> public void start() {
> errStr = null;
> thread = new Thread(this);
> thread.setName("Capture");
> thread.start();
> }
>
> public void stop() {
> thread = null;
> }
>
> private void shutDown(String message) {
> if ((errStr = message) != null && thread != null) {
> thread = null;
> samplingGraph.stop();
> loadB.setEnabled(true);
> playB.setEnabled(true);
> pausB.setEnabled(false);
> auB.setEnabled(true);
> aiffB.setEnabled(true);
> waveB.setEnabled(true);
> captB.setText("Record");
> System.err.println(errStr);
> samplingGraph.repaint();
> }
> }
>
> public void run() {
>
> duration = 0;
> audioInputStream = null;
>
> // define the required attributes for our line,
> // and make sure a compatible line is supported.
>
> AudioFormat format = formatControls.getFormat();
> DataLine.Info info = new DataLine.Info(TargetDataLine.class,
> format);
>
> if (!AudioSystem.isLineSupported(info)) {
> shutDown("Line matching " + info + " not supported.");
> return;
> }
>
> // get and open the target data line for capture.
>
> try {
> line = (TargetDataLine) AudioSystem.getLine(info);
> line.open(format, line.getBufferSize());
> } catch (LineUnavailableException ex) {
> shutDown("Unable to open the line: " + ex);
> return;
> } catch (SecurityException ex) {
> shutDown(ex.toString());
> JavaSound.showInfoDialog();
> return;
> } catch (Exception ex) {
> shutDown(ex.toString());
> return;
> }
>
> // play back the captured audio data
> ByteArrayOutputStream out = new ByteArrayOutputStream();
> int frameSizeInBytes = format.getFrameSize();
> int bufferLengthInFrames = line.getBufferSize() / 8;
> int bufferLengthInBytes = bufferLengthInFrames *
> frameSizeInBytes;
> byte[] data = new byte[bufferLengthInBytes];
> int numBytesRead;
>
> line.start();
>
> while (thread != null) {
> if((numBytesRead = line.read(data, 0, bufferLengthInBytes))
> == -1) {
> break;
> }
> out.write(data, 0, numBytesRead);
> }
>
> // we reached the end of the stream. stop and close the line.
> line.stop();
> line.close();
> line = null;
>
> // stop and close the output stream
> try {
> out.flush();
> out.close();
> } catch (IOException ex) {
> ex.printStackTrace();
> }
>
> // load bytes into the audio input stream for playback
>
> byte audioBytes[] = out.toByteArray();
> ByteArrayInputStream bais = new
> ByteArrayInputStream(audioBytes);
> audioInputStream = new AudioInputStream(bais, format,
> audioBytes.length / frameSizeInBytes);
>
> long milliseconds = (long)((audioInputStream.getFrameLength() *
> 1000) / format.getFrameRate());
> duration = milliseconds / 1000.0;
>
> try {
> audioInputStream.reset();
> } catch (Exception ex) {
> ex.printStackTrace();
> return;
> }
>
> samplingGraph.createWaveForm(audioBytes);
> }
> } // End class Capture
>
>
> /**
> * Controls for the AudioFormat.
> */
> class FormatControls extends JPanel {
>
> Vector groups = new Vector();
> JToggleButton linrB, ulawB, alawB, rate8B, rate11B, rate16B,
> rate22B, rate44B;
> JToggleButton size8B, size16B, signB, unsignB, litB, bigB,
> monoB,sterB;
>
> public FormatControls() {
> setLayout(new GridLayout(0,1));
> EmptyBorder eb = new EmptyBorder(0,0,0,5);
> BevelBorder bb = new BevelBorder(BevelBorder.LOWERED);
> CompoundBorder cb = new CompoundBorder(eb, bb);
> setBorder(new CompoundBorder(cb, new EmptyBorder(8,5,5,5)));
> JPanel p1 = new JPanel();
> ButtonGroup encodingGroup = new ButtonGroup();
> linrB = addToggleButton(p1, encodingGroup, "linear", true);
> ulawB = addToggleButton(p1, encodingGroup, "ulaw", false);
> alawB = addToggleButton(p1, encodingGroup, "alaw", false);
> add(p1);
> groups.addElement(encodingGroup);
>
> JPanel p2 = new JPanel();
> JPanel p2b = new JPanel();
> ButtonGroup sampleRateGroup = new ButtonGroup();
> rate8B = addToggleButton(p2, sampleRateGroup, "8000", false);
> rate11B = addToggleButton(p2, sampleRateGroup, "11025", false);
> rate16B = addToggleButton(p2b, sampleRateGroup, "16000", false);
> rate22B = addToggleButton(p2b, sampleRateGroup, "22050", false);
> rate44B = addToggleButton(p2b, sampleRateGroup, "44100", true);
> add(p2);
> add(p2b);
> groups.addElement(sampleRateGroup);
>
> JPanel p3 = new JPanel();
> ButtonGroup sampleSizeInBitsGroup = new ButtonGroup();
> size8B = addToggleButton(p3, sampleSizeInBitsGroup, "8", false);
> size16B = addToggleButton(p3, sampleSizeInBitsGroup, "16",
> true);
> add(p3);
> groups.addElement(sampleSizeInBitsGroup);
>
> JPanel p4 = new JPanel();
> ButtonGroup signGroup = new ButtonGroup();
> signB = addToggleButton(p4, signGroup, "signed", true);
> unsignB = addToggleButton(p4, signGroup, "unsigned", false);
> add(p4);
> groups.addElement(signGroup);
>
> JPanel p5 = new JPanel();
> ButtonGroup endianGroup = new ButtonGroup();
> litB = addToggleButton(p5, endianGroup, "little endian", false);
> bigB = addToggleButton(p5, endianGroup, "big endian", true);
> add(p5);
> groups.addElement(endianGroup);
>
> JPanel p6 = new JPanel();
> ButtonGroup channelsGroup = new ButtonGroup();
> monoB = addToggleButton(p6, channelsGroup, "mono", false);
> sterB = addToggleButton(p6, channelsGroup, "stereo", true);
> add(p6);
> groups.addElement(channelsGroup);
> }
>
> private JToggleButton addToggleButton(JPanel p, ButtonGroup g,
> String name, boolean state) {
> JToggleButton b = new JToggleButton(name, state);
> p.add(b);
> g.add(b);
> return b;
> }
>
> public AudioFormat getFormat() {
>
> Vector v = new Vector(groups.size());
> for (int i = 0; i < groups.size(); i++) {
> ButtonGroup g = (ButtonGroup) groups.get(i);
> for (Enumeration e = g.getElements();e.hasMoreElements();) {
> AbstractButton b = (AbstractButton) e.nextElement();
> if (b.isSelected()) {
> v.add(b.getText());
> break;
> }
> }
> }
>
> AudioFormat.Encoding encoding = AudioFormat.Encoding.ULAW;
> String encString = (String) v.get(0);
> float rate = Float.valueOf((String) v.get(1)).floatValue();
> int sampleSize = Integer.valueOf((String) v.get(2)).intValue();
> String signedString = (String) v.get(3);
> boolean bigEndian = ((String) v.get(4)).startsWith("big");
> int channels = ((String) v.get(5)).equals("mono") ? 1 : 2;
>
> if (encString.equals("linear")) {
> if (signedString.equals("signed")) {
> encoding = AudioFormat.Encoding.PCM_SIGNED;
> } else {
> encoding = AudioFormat.Encoding.PCM_UNSIGNED;
> }
> } else if (encString.equals("alaw")) {
> encoding = AudioFormat.Encoding.ALAW;
> }
> return new AudioFormat(encoding, rate, sampleSize,
> channels, (sampleSize/8)*channels, rate,
> bigEndian);
> }
>
>
> public void setFormat(AudioFormat format) {
> AudioFormat.Encoding type = format.getEncoding();
> if (type == AudioFormat.Encoding.ULAW) {
> ulawB.doClick();
> } else if (type == AudioFormat.Encoding.ALAW) {
> alawB.doClick();
> } else if (type == AudioFormat.Encoding.PCM_SIGNED) {
> linrB.doClick(); signB.doClick();
> } else if (type == AudioFormat.Encoding.PCM_UNSIGNED) {
> linrB.doClick(); unsignB.doClick();
> }
> float rate = format.getFrameRate();
> if (rate == 8000) {
> rate8B.doClick();
> } else if (rate == 11025) {
> rate11B.doClick();
> } else if (rate == 16000) {
> rate16B.doClick();
> } else if (rate == 22050) {
> rate22B.doClick();
> } else if (rate == 44100) {
> rate44B.doClick();
> }
> switch (format.getSampleSizeInBits()) {
> case 8 : size8B.doClick(); break;
> case 16 : size16B.doClick(); break;
> }
> if (format.isBigEndian()) {
> bigB.doClick();
> } else {
> litB.doClick();
> }
> if (format.getChannels() == 1) {
> monoB.doClick();
> } else {
> sterB.doClick();
> }
> }
> } // End class FormatControls
>
>
> /**
> * Render a WaveForm.
> */
> class SamplingGraph extends JPanel implements Runnable {
>
> private Thread thread;
> private Font font10 = new Font("serif", Font.PLAIN, 10);
> private Font font12 = new Font("serif", Font.PLAIN, 12);
> Color jfcBlue = new Color(204, 204, 255);
> Color pink = new Color(255, 175, 175);
>
>
> public SamplingGraph() {
> setBackground(new Color(20, 20, 20));
> }
>
>
> public void createWaveForm(byte[] audioBytes) {
>
> lines.removeAllElements(); // clear the old vector
>
> AudioFormat format = audioInputStream.getFormat();
> if (audioBytes == null) {
> try {
> audioBytes = new byte[
> (int) (audioInputStream.getFrameLength()
> * format.getFrameSize())];
> audioInputStream.read(audioBytes);
> } catch (Exception ex) {
> reportStatus(ex.toString());
> return;
> }
> }
>
> Dimension d = getSize();
> int w = d.width;
> int h = d.height-15;
> int[] audioData = null;
> if (format.getSampleSizeInBits() == 16) {
> int nlengthInSamples = audioBytes.length / 2;
> audioData = new int[nlengthInSamples];
> if (format.isBigEndian()) {
> for (int i = 0; i < nlengthInSamples; i++) {
> /* First byte is MSB (high order) */
> int MSB = (int) audioBytes[2*i];
> /* Second byte is LSB (low order) */
> int LSB = (int) audioBytes[2*i+1];
> audioData[i] = MSB << 8 | (255 & LSB);
> }
> } else {
> for (int i = 0; i < nlengthInSamples; i++) {
> /* First byte is LSB (low order) */
> int LSB = (int) audioBytes[2*i];
> /* Second byte is MSB (high order) */
> int MSB = (int) audioBytes[2*i+1];
> audioData[i] = MSB << 8 | (255 & LSB);
> }
> }
> } else if (format.getSampleSizeInBits() == 8) {
> int nlengthInSamples = audioBytes.length;
> audioData = new int[nlengthInSamples];
> if (format.getEncoding().toString().startsWith("PCM_SIGN"))
> {
> for (int i = 0; i < audioBytes.length; i++) {
> audioData[i] = audioBytes[i];
> }
> } else {
> for (int i = 0; i < audioBytes.length; i++) {
> audioData[i] = audioBytes[i] - 128;
> }
> }
> }
>
> int frames_per_pixel = audioBytes.length /
> format.getFrameSize()/w;
> byte my_byte = 0;
> double y_last = 0;
> int numChannels = format.getChannels();
> for (double x = 0; x < w && audioData != null; x++) {
> int idx = (int) (frames_per_pixel * numChannels * x);
> if (format.getSampleSizeInBits() == 8) {
> my_byte = (byte) audioData[idx];
> } else {
> my_byte = (byte) (128 * audioData[idx] / 32768 );
> }
> double y_new = (double) (h * (128 - my_byte) / 256);
> lines.add(new Line2D.Double(x, y_last, x, y_new));
> y_last = y_new;
> }
>
> repaint();
> }
>
>
> public void paint(Graphics g) {
>
> Dimension d = getSize();
> int w = d.width;
> int h = d.height;
> int INFOPAD = 15;
>
> Graphics2D g2 = (Graphics2D) g;
> g2.setBackground(getBackground());
> g2.clearRect(0, 0, w, h);
> g2.setColor(Color.white);
> g2.fillRect(0, h-INFOPAD, w, INFOPAD);
>
> if (errStr != null) {
> g2.setColor(jfcBlue);
> g2.setFont(new Font("serif", Font.BOLD, 18));
> g2.drawString("ERROR", 5, 20);
> AttributedString as = new AttributedString(errStr);
> as.addAttribute(TextAttribute.FONT, font12, 0,
> errStr.length());
> AttributedCharacterIterator aci = as.getIterator();
> FontRenderContext frc = g2.getFontRenderContext();
> LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);
> float x = 5, y = 25;
> lbm.setPosition(0);
> while (lbm.getPosition() < errStr.length()) {
> TextLayout tl = lbm.nextLayout(w-x-5);
> if (!tl.isLeftToRight()) {
> x = w - tl.getAdvance();
> }
> tl.draw(g2, x, y += tl.getAscent());
> y += tl.getDescent() + tl.getLeading();
> }
> } else if (capture.thread != null) {
> g2.setColor(Color.black);
> g2.setFont(font12);
> g2.drawString("Length: " + String.valueOf(seconds), 3, h-4);
> } else {
> g2.setColor(Color.black);
> g2.setFont(font12);
> g2.drawString("File: " + fileName + " Length: " +
> String.valueOf(duration) + " Position: " + String.valueOf(seconds), 3,
> h-4);
>
> if (audioInputStream != null) {
> // .. render sampling graph ..
> g2.setColor(jfcBlue);
> for (int i = 1; i < lines.size(); i++) {
> g2.draw((Line2D) lines.get(i));
> }
>
> // .. draw current position ..
> if (seconds != 0) {
> double loc = seconds/duration*w;
> g2.setColor(pink);
> g2.setStroke(new BasicStroke(3));
> g2.draw(new Line2D.Double(loc, 0, loc,
> h-INFOPAD-2));
> }
> }
> }
> }
>
> public void start() {
> thread = new Thread(this);
> thread.setName("SamplingGraph");
> thread.start();
> seconds = 0;
> }
>
> public void stop() {
> if (thread != null) {
> thread.interrupt();
> }
> thread = null;
> }
>
> public void run() {
> seconds = 0;
> while (thread != null) {
> if ((playback.line != null) && (playback.line.isOpen()) ) {
>
> long milliseconds =
> (long)(playback.line.getMicrosecondPosition() / 1000);
> seconds = milliseconds / 1000.0;
> } else if ( (capture.line != null) &&
> (capture.line.isActive()) ) {
>
> long milliseconds =
> (long)(capture.line.getMicrosecondPosition() / 1000);
> seconds = milliseconds / 1000.0;
> }
>
> try { thread.sleep(100); } catch (Exception e) { break; }
>
> repaint();
>
> while ((capture.line != null && !capture.line.isActive()) ||
> (playback.line != null && !playback.line.isOpen()))
> {
> try { thread.sleep(10); } catch (Exception e) { break; }
> }
> }
> seconds = 0;
> repaint();
> }
> } // End class SamplingGraph
>
>
>
>
> public static void main(String s[]) {
> CapturePlayback capturePlayback = new CapturePlayback();
> capturePlayback.open();
> JFrame f = new JFrame("Capture/Playback");
> f.addWindowListener(new WindowAdapter() {
> public void windowClosing(WindowEvent e) { System.exit(0); }
> });
> f.getContentPane().add("Center", capturePlayback);
> f.pack();
> Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
> int w = 720;
> int h = 340;
> f.setLocation(screenSize.width/2 - w/2, screenSize.height/2 - h/2);
> f.setSize(w, h);
> f.show();
> }
> }
|
| |
|
| |
 |
gg

|
Posted: 2003-9-12 13:56:00 |
Top |
java-programmer >> Java Sound
Thank you. So there is no way around the problem then?
"Kris Gutta" <email***@***.com> wrote in message
news:email***@***.com...
> Java Sound doesn't use any temperary files to buffer the audio. It
> actually buffers the audio in the memorey. So the more recording you
> do the more memorey it takes and at some point you will run out of
> memorey and the application will fails.
>
> Hope this answers your question.
>
> -kris
>
> "gg" <email***@***.com> wrote in message
news:<baS2b.59448$K44.685@edtnps84>...
> > I was trying to learn java sound and downloaded the Java Sound Demo from
> > Sun. The recording part of it part seems to fail to produce the stream
for
> > playback when the recording length exceed about half an hour to 3/4 hr.
> > I tried examineing the code to find the cause of it ( I though it could
be
> > fouled up by graphing) or something with the stream for too long and
> > consumed too much RAM..
> >
> > I look for documentation whether the sound api automatically create
> > temporary file to buffer the stream and failed.
> >
> > Can someone point me the documentation showing how to oevercome the
stream
> > length problem length?
> >
> >
> > the code for the recording and playback is as follows:
> > /*
> > * @(#)CapturePlayback.java 1.11 99/12/03
> > *
> > * Copyright (c) 1999 Sun Microsystems, Inc. All Rights Reserved.
> > *
> > * Sun grants you ("Licensee") a non-exclusive, royalty free, license to
> > use,
> > * modify and redistribute this software in source and binary code form,
> > * provided that i) this copyright notice and license appear on all
copies
> > of
> > * the software; and ii) Licensee does not utilize the software in a
manner
> > * which is disparaging to Sun.
> > *
> > * This software is provided "AS IS," without a warranty of any kind.
ALL
> > * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
INCLUDING
> > ANY
> > * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
OR
> > * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL
NOT BE
> > * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
> > MODIFYING
> > * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN
OR
> > ITS
> > * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR
DIRECT,
> > * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES,
HOWEVER
> > * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE
USE
> > OF
> > * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
> > * POSSIBILITY OF SUCH DAMAGES.
> > *
> > * This software is not designed or intended for use in on-line control
of
> > * aircraft, air traffic, aircraft navigation or aircraft
communications; or
> > in
> > * the design, construction, operation or maintenance of any nuclear
> > * facility. Licensee represents and warrants that it will not use or
> > * redistribute the Software for such purposes.
> > */
> >
> >
> > import java.awt.*;
> > import java.awt.event.*;
> > import java.awt.geom.Line2D;
> > import javax.swing.*;
> > import javax.swing.event.*;
> > import javax.swing.border.*;
> > import java.util.Vector;
> > import java.util.Enumeration;
> > import java.io.*;
> > import javax.sound.sampled.*;
> > import java.awt.font.*;
> > import java.text.*;
> >
> >
> >
> >
> > /**
> > * Capture/Playback sample. Record audio in different formats
> > * and then playback the recorded audio. The captured audio can
> > * be saved either as a WAVE, AU or AIFF. Or load an audio file
> > * for streaming playback.
> > *
> > * @version @(#)CapturePlayback.java 1.11 99/12/03
> > * @author Brian Lichtenwalter
> > */
> > public class CapturePlayback extends JPanel implements ActionListener,
> > ControlContext {
> >
> > final int bufSize = 16384;
> >
> > FormatControls formatControls = new FormatControls();
> > Capture capture = new Capture();
> > Playback playback = new Playback();
> >
> > AudioInputStream audioInputStream;
> > SamplingGraph samplingGraph;
> >
> > JButton playB, captB, pausB, loadB, newB;
> > JButton auB, aiffB, waveB;
> > JTextField textField;
> >
> > String fileName = "untitled";
> > String errStr;
> > double duration, seconds;
> > File file;
> > Vector lines = new Vector();
> >
> >
> >
> > public CapturePlayback() {
> > setLayout(new BorderLayout());
> > EmptyBorder eb = new EmptyBorder(5,5,5,5);
> > SoftBevelBorder sbb = new
SoftBevelBorder(SoftBevelBorder.LOWERED);
> > setBorder(new EmptyBorder(5,5,5,5));
> >
> > JPanel p1 = new JPanel();
> > p1.setLayout(new BoxLayout(p1, BoxLayout.X_AXIS));
> > p1.add(formatControls);
> >
> > JPanel p2 = new JPanel();
> > p2.setBorder(sbb);
> > p2.setLayout(new BoxLayout(p2, BoxLayout.Y_AXIS));
> >
> > JPanel buttonsPanel = new JPanel();
> > buttonsPanel.setBorder(new EmptyBorder(10,0,5,0));
> > playB = addButton("Play", buttonsPanel, false);
> > captB = addButton("Record", buttonsPanel, true);
> > pausB = addButton("Pause", buttonsPanel, false);
> > loadB = addButton("Load...", buttonsPanel, true);
> > newB = addButton("New", buttonsPanel, true);
> > p2.add(buttonsPanel);
> >
> > JPanel samplingPanel = new JPanel(new BorderLayout());
> > eb = new EmptyBorder(10,20,20,20);
> > samplingPanel.setBorder(new CompoundBorder(eb, sbb));
> > samplingPanel.add(samplingGraph = new SamplingGraph());
> > p2.add(samplingPanel);
> >
> > JPanel savePanel = new JPanel();
> > savePanel.setLayout(new BoxLayout(savePanel, BoxLayout.Y_AXIS));
> >
> > JPanel saveTFpanel = new JPanel();
> > saveTFpanel.add(new JLabel("File to save: "));
> > saveTFpanel.add(textField = new JTextField(fileName));
> > textField.setPreferredSize(new Dimension(140,25));
> > savePanel.add(saveTFpanel);
> >
> > JPanel saveBpanel = new JPanel();
> > auB = addButton("Save AU", saveBpanel, false);
> > aiffB = addButton("Save AIFF", saveBpanel, false);
> > waveB = addButton("Save WAVE", saveBpanel, false);
> > savePanel.add(saveBpanel);
> >
> > p2.add(savePanel);
> >
> > p1.add(p2);
> > add(p1);
> > }
> >
> >
> > public void open() { }
> >
> >
> > public void close() {
> > if (playback.thread != null) {
> > playB.doClick(0);
> > }
> > if (capture.thread != null) {
> > captB.doClick(0);
> > }
> > }
> >
> >
> > private JButton addButton(String name, JPanel p, boolean state) {
> > JButton b = new JButton(name);
> > b.addActionListener(this);
> > b.setEnabled(state);
> > p.add(b);
> > return b;
> > }
> >
> >
> > public void actionPerformed(ActionEvent e) {
> > Object obj = e.getSource();
> > if (obj.equals(auB)) {
> > saveToFile(textField.getText().trim(),
AudioFileFormat.Type.AU);
> > } else if (obj.equals(aiffB)) {
> > saveToFile(textField.getText().trim(),
> > AudioFileFormat.Type.AIFF);
> > } else if (obj.equals(waveB)) {
> > saveToFile(textField.getText().trim(),
> > AudioFileFormat.Type.WAVE);
> > } else if (obj.equals(playB)) {
> > if (playB.getText().startsWith("Play")) {
> > playback.start();
> > samplingGraph.start();
> > captB.setEnabled(false);
> > pausB.setEnabled(true);
> > playB.setText("Stop");
> > } else {
> > playback.stop();
> > samplingGraph.stop();
> > captB.setEnabled(true);
> > pausB.setEnabled(false);
> > playB.setText("Play");
> > }
> > } else if (obj.equals(captB)) {
> > if (captB.getText().startsWith("Record")) {
> > file = null;
> > capture.start();
> > fileName = "untitled";
> > samplingGraph.start();
> > loadB.setEnabled(false);
> > playB.setEnabled(false);
> > pausB.setEnabled(true);
> > auB.setEnabled(false);
> > aiffB.setEnabled(false);
> > waveB.setEnabled(false);
> > captB.setText("Stop");
> > } else {
> > lines.removeAllElements();
> > capture.stop();
> > samplingGraph.stop();
> > loadB.setEnabled(true);
> > playB.setEnabled(true);
> > pausB.setEnabled(false);
> > auB.setEnabled(true);
> > aiffB.setEnabled(true);
> > waveB.setEnabled(true);
> > captB.setText("Record");
> > }
> > } else if (obj.equals(pausB)) {
> > if (pausB.getText().startsWith("Pause")) {
> > if (capture.thread != null) {
> > capture.line.stop();
> > } else {
> > if (playback.thread != null) {
> > playback.line.stop();
> > }
> > }
> > pausB.setText("Resume");
> > } else {
> > if (capture.thread != null) {
> > capture.line.start();
> > } else {
> > if (playback.thread != null) {
> > playback.line.start();
> > }
> > }
> > pausB.setText("Pause");
> > }
> > } else if (obj.equals(loadB)) {
> > try {
> > File file = new File(System.getProperty("user.dir"));
> > JFileChooser fc = new JFileChooser(file);
> > fc.setFileFilter(new javax.swing.filechooser.FileFilter
() {
> > public boolean accept(File f) {
> > if (f.isDirectory()) {
> > return true;
> > }
> > String name = f.getName();
> > if (name.endsWith(".au") ||
name.endsWith(".wav") ||
> > name.endsWith(".aiff") || name.endsWith(".aif")) {
> > return true;
> > }
> > return false;
> > }
> > public String getDescription() {
> > return ".au, .wav, .aif";
> > }
> > });
> >
> > if (fc.showOpenDialog(null) ==
JFileChooser.APPROVE_OPTION)
> > {
> > createAudioInputStream(fc.getSelectedFile(), true);
> > }
> > } catch (SecurityException ex) {
> > JavaSound.showInfoDialog();
> > ex.printStackTrace();
> > } catch (Exception ex) {
> > ex.printStackTrace();
> > }
> >
> > } else if (obj.equals(newB)) // 20030823 GG added this this else
if
> > clause to deal with not having to close to satrt new recording
> > if (captB.getText().startsWith("Record")) {
> > file = null;
> > capture.start();
> > fileName = "untitled";
> > samplingGraph.start();
> >
> > captB.setText("Stop");
> > } else {
> > lines.removeAllElements();
> > capture.stop();
> > samplingGraph.stop();
> > }
> >
> > loadB.setEnabled(false);
> > playB.setEnabled(false);
> > pausB.setEnabled(true);
> > auB.setEnabled(false);
> > aiffB.setEnabled(false);
> > waveB.setEnabled(false);
> > }
> > }
> >
> >
> > public void createAudioInputStream(File file, boolean
updateComponents)
> > {
> > if (file != null && file.isFile()) {
> > try {
> > this.file = file;
> > errStr = null;
> > audioInputStream =
AudioSystem.getAudioInputStream(file);
> > playB.setEnabled(true);
> > fileName = file.getName();
> > long milliseconds =
> > (long)((audioInputStream.getFrameLength() * 1000) /
> > audioInputStream.getFormat().getFrameRate());
> > duration = milliseconds / 1000.0;
> > auB.setEnabled(true);
> > aiffB.setEnabled(true);
> > waveB.setEnabled(true);
> > if (updateComponents) {
> >
formatControls.setFormat(audioInputStream.getFormat());
> > samplingGraph.createWaveForm(null);
> > }
> > } catch (Exception ex) {
> > reportStatus(ex.toString());
> > }
> > } else {
> > reportStatus("Audio file required.");
> > }
> > }
> >
> >
> > public void saveToFile(String name, AudioFileFormat.Type fileType) {
> >
> > if (audioInputStream == null) {
> > reportStatus("No loaded audio to save");
> > return;
> > } else if (file != null) {
> > createAudioInputStream(file, false);
> > }
> >
> > // reset to the beginnning of the captured data
> > try {
> > audioInputStream.reset();
> > } catch (Exception e) {
> > reportStatus("Unable to reset stream " + e);
> > return;
> > }
> >
> > File file = new File(fileName = name);
> > try {
> > if (AudioSystem.write(audioInputStream, fileType, file)
== -1) {
> > throw new IOException("Problems writing to file");
> > }
> > } catch (Exception ex) { reportStatus(ex.toString()); }
> > samplingGraph.repaint();
> > }
> >
> >
> > private void reportStatus(String msg) {
> > if ((errStr = msg) != null) {
> > System.out.println(errStr);
> > samplingGraph.repaint();
> > }
> > }
> >
> >
> > /**
> > * Write data to the OutputChannel.
> > */
> > public class Playback implements Runnable {
> >
> > SourceDataLine line;
> > Thread thread;
> >
> > public void start() {
> > errStr = null;
> > thread = new Thread(this);
> > thread.setName("Playback");
> > thread.start();
> > }
> >
> > public void stop() {
> > thread = null;
> > }
> >
> > private void shutDown(String message) {
> > if ((errStr = message) != null) {
> > System.err.println(errStr);
> > samplingGraph.repaint();
> > }
> > if (thread != null) {
> > thread = null;
> > samplingGraph.stop();
> > captB.setEnabled(true);
> > pausB.setEnabled(false);
> > playB.setText("Play");
> > }
> > }
> >
> > public void run() {
> >
> > // reload the file if loaded by file
> > if (file != null) {
> > createAudioInputStream(file, false);
> > }
> >
> > // make sure we have something to play
> > if (audioInputStream == null) {
> > shutDown("No loaded audio to play back");
> > return;
> > }
> > // reset to the beginnning of the stream
> > try {
> > audioInputStream.reset();
> > } catch (Exception e) {
> > shutDown("Unable to reset the stream\n" + e);
> > return;
> > }
> >
> > // get an AudioInputStream of the desired format for
playback
> > AudioFormat format = formatControls.getFormat();
> > AudioInputStream playbackInputStream =
> > AudioSystem.getAudioInputStream(format, audioInputStream);
> >
> > if (playbackInputStream == null) {
> > shutDown("Unable to convert stream of format " +
> > audioInputStream + " to format " + format);
> > return;
> > }
> >
> > // define the required attributes for our line,
> > // and make sure a compatible line is supported.
> >
> > DataLine.Info info = new DataLine.Info(SourceDataLine.class,
> > format);
> > if (!AudioSystem.isLineSupported(info)) {
> > shutDown("Line matching " + info + " not supported.");
> > return;
> > }
> >
> > // get and open the source data line for playback.
> >
> > try {
> > line = (SourceDataLine) AudioSystem.getLine(info);
> > line.open(format, bufSize);
> > } catch (LineUnavailableException ex) {
> > shutDown("Unable to open the line: " + ex);
> > return;
> > }
> >
> > // play back the captured audio data
> >
> > int frameSizeInBytes = format.getFrameSize();
> > int bufferLengthInFrames = line.getBufferSize() / 8;
> > int bufferLengthInBytes = bufferLengthInFrames *
> > frameSizeInBytes;
> > byte[] data = new byte[bufferLengthInBytes];
> > int numBytesRead = 0;
> >
> > // start the source data line
> > line.start();
> >
> > while (thread != null) {
> > try {
> > if ((numBytesRead = playbackInputStream.read(data))
> > == -1) {
> > break;
> > }
> > int numBytesRemaining = numBytesRead;
> > while (numBytesRemaining > 0 ) {
> > numBytesRemaining -= line.write(data, 0,
> > numBytesRemaining);
> > }
> > } catch (Exception e) {
> > shutDown("Error during playback: " + e);
> > break;
> > }
> > }
> > // we reached the end of the stream. let the data play out,
> > then
> > // stop and close the line.
> > if (thread != null) {
> > line.drain();
> > }
> > line.stop();
> > line.close();
> > line = null;
> > shutDown(null);
> > }
> > } // End class Playback
> >
> >
> > /**
> > * Reads data from the input channel and writes to the output stream
> > */
> > class Capture implements Runnable {
> >
> > TargetDataLine line;
> > Thread thread;
> >
> > public void start() {
> > errStr = null;
> > thread = new Thread(this);
> > thread.setName("Capture");
> > thread.start();
> > }
> >
> > public void stop() {
> > thread = null;
> > }
> >
> > private void shutDown(String message) {
> > if ((errStr = message) != null && thread != null) {
> > thread = null;
> > samplingGraph.stop();
> > loadB.setEnabled(true);
> > playB.setEnabled(true);
> > pausB.setEnabled(false);
> > auB.setEnabled(true);
> > aiffB.setEnabled(true);
> > waveB.setEnabled(true);
> > captB.setText("Record");
> > System.err.println(errStr);
> > samplingGraph.repaint();
> > }
> > }
> >
> > public void run() {
> >
> > duration = 0;
> > audioInputStream = null;
> >
> > // define the required attributes for our line,
> > // and make sure a compatible line is supported.
> >
> > AudioFormat format = formatControls.getFormat();
> > DataLine.Info info = new DataLine.Info(TargetDataLine.class,
> > format);
> >
> > if (!AudioSystem.isLineSupported(info)) {
> > shutDown("Line matching " + info + " not supported.");
> > return;
> > }
> >
> > // get and open the target data line for capture.
> >
> > try {
> > line = (TargetDataLine) AudioSystem.getLine(info);
> > line.open(format, line.getBufferSize());
> > } catch (LineUnavailableException ex) {
> > shutDown("Unable to open the line: " + ex);
> > return;
> > } catch (SecurityException ex) {
> > shutDown(ex.toString());
> > JavaSound.showInfoDialog();
> > return;
> > } catch (Exception ex) {
> > shutDown(ex.toString());
> > return;
> > }
> >
> > // play back the captured audio data
> > ByteArrayOutputStream out = new ByteArrayOutputStream();
> > int frameSizeInBytes = format.getFrameSize();
> > int bufferLengthInFrames = line.getBufferSize() / 8;
> > int bufferLengthInBytes = bufferLengthInFrames *
> > frameSizeInBytes;
> > byte[] data = new byte[bufferLengthInBytes];
> > int numBytesRead;
> >
> > line.start();
> >
> > while (thread != null) {
> > if((numBytesRead = line.read(data, 0,
bufferLengthInBytes))
> > == -1) {
> > break;
> > }
> > out.write(data, 0, numBytesRead);
> > }
> >
> > // we reached the end of the stream. stop and close the
line.
> > line.stop();
> > line.close();
> > line = null;
> >
> > // stop and close the output stream
> > try {
> > out.flush();
> > out.close();
> > } catch (IOException ex) {
> > ex.printStackTrace();
> > }
> >
> > // load bytes into the audio input stream for playback
> >
> > byte audioBytes[] = out.toByteArray();
> > ByteArrayInputStream bais = new
> > ByteArrayInputStream(audioBytes);
> > audioInputStream = new AudioInputStream(bais, format,
> > audioBytes.length / frameSizeInBytes);
> >
> > long milliseconds =
(long)((audioInputStream.getFrameLength() *
> > 1000) / format.getFrameRate());
> > duration = milliseconds / 1000.0;
> >
> > try {
> > audioInputStream.reset();
> > } catch (Exception ex) {
> > ex.printStackTrace();
> > return;
> > }
> >
> > samplingGraph.createWaveForm(audioBytes);
> > }
> > } // End class Capture
> >
> >
> > /**
> > * Controls for the AudioFormat.
> > */
> > class FormatControls extends JPanel {
> >
> > Vector groups = new Vector();
> > JToggleButton linrB, ulawB, alawB, rate8B, rate11B, rate16B,
> > rate22B, rate44B;
> > JToggleButton size8B, size16B, signB, unsignB, litB, bigB,
> > monoB,sterB;
> >
> > public FormatControls() {
> > setLayout(new GridLayout(0,1));
> > EmptyBorder eb = new EmptyBorder(0,0,0,5);
> > BevelBorder bb = new BevelBorder(BevelBorder.LOWERED);
> > CompoundBorder cb = new CompoundBorder(eb, bb);
> > setBorder(new CompoundBorder(cb, new EmptyBorder(8,5,5,5)));
> > JPanel p1 = new JPanel();
> > ButtonGroup encodingGroup = new ButtonGroup();
> > linrB = addToggleButton(p1, encodingGroup, "linear", true);
> > ulawB = addToggleButton(p1, encodingGroup, "ulaw", false);
> > alawB = addToggleButton(p1, encodingGroup, "alaw", false);
> > add(p1);
> > groups.addElement(encodingGroup);
> >
> > JPanel p2 = new JPanel();
> > JPanel p2b = new JPanel();
> > ButtonGroup sampleRateGroup = new ButtonGroup();
> > rate8B = addToggleButton(p2, sampleRateGroup, "8000",
false);
> > rate11B = addToggleButton(p2, sampleRateGroup, "11025",
false);
> > rate16B = addToggleButton(p2b, sampleRateGroup, "16000",
false);
> > rate22B = addToggleButton(p2b, sampleRateGroup, "22050",
false);
> > rate44B = addToggleButton(p2b, sampleRateGroup, "44100",
true);
> > add(p2);
> > add(p2b);
> > groups.addElement(sampleRateGroup);
> >
> > JPanel p3 = new JPanel();
> > ButtonGroup sampleSizeInBitsGroup = new ButtonGroup();
> > size8B = addToggleButton(p3, sampleSizeInBitsGroup, "8",
false);
> > size16B = addToggleButton(p3, sampleSizeInBitsGroup, "16",
> > true);
> > add(p3);
> > groups.addElement(sampleSizeInBitsGroup);
> >
> > JPanel p4 = new JPanel();
> > ButtonGroup signGroup = new ButtonGroup();
> > signB = addToggleButton(p4, signGroup, "signed", true);
> > unsignB = addToggleButton(p4, signGroup, "unsigned", false);
> > add(p4);
> > groups.addElement(signGroup);
> >
> > JPanel p5 = new JPanel();
> > ButtonGroup endianGroup = new ButtonGroup();
> > litB = addToggleButton(p5, endianGroup, "little endian",
false);
> > bigB = addToggleButton(p5, endianGroup, "big endian", true);
> > add(p5);
> > groups.addElement(endianGroup);
> >
> > JPanel p6 = new JPanel();
> > ButtonGroup channelsGroup = new ButtonGroup();
> > monoB = addToggleButton(p6, channelsGroup, "mono", false);
> > sterB = addToggleButton(p6, channelsGroup, "stereo", true);
> > add(p6);
> > groups.addElement(channelsGroup);
> > }
> >
> > private JToggleButton addToggleButton(JPanel p, ButtonGroup g,
> > String name, boolean state) {
> > JToggleButton b = new JToggleButton(name, state);
> > p.add(b);
> > g.add(b);
> > return b;
> > }
> >
> > public AudioFormat getFormat() {
> >
> > Vector v = new Vector(groups.size());
> > for (int i = 0; i < groups.size(); i++) {
> > ButtonGroup g = (ButtonGroup) groups.get(i);
> > for (Enumeration e =
g.getElements();e.hasMoreElements();) {
> > AbstractButton b = (AbstractButton) e.nextElement();
> > if (b.isSelected()) {
> > v.add(b.getText());
> > break;
> > }
> > }
> > }
> >
> > AudioFormat.Encoding encoding = AudioFormat.Encoding.ULAW;
> > String encString = (String) v.get(0);
> > float rate = Float.valueOf((String) v.get(1)).floatValue();
> > int sampleSize = Integer.valueOf((String)
v.get(2)).intValue();
> > String signedString = (String) v.get(3);
> > boolean bigEndian = ((String) v.get(4)).startsWith("big");
> > int channels = ((String) v.get(5)).equals("mono") ? 1 : 2;
> >
> > if (encString.equals("linear")) {
> > if (signedString.equals("signed")) {
> > encoding = AudioFormat.Encoding.PCM_SIGNED;
> > } else {
> > encoding = AudioFormat.Encoding.PCM_UNSIGNED;
> > }
> > } else if (encString.equals("alaw")) {
> > encoding = AudioFormat.Encoding.ALAW;
> > }
> > return new AudioFormat(encoding, rate, sampleSize,
> > channels, (sampleSize/8)*channels, rate,
> > bigEndian);
> > }
> >
> >
> > public void setFormat(AudioFormat format) {
> > AudioFormat.Encoding type = format.getEncoding();
> > if (type == AudioFormat.Encoding.ULAW) {
> > ulawB.doClick();
> > } else if (type == AudioFormat.Encoding.ALAW) {
> > alawB.doClick();
> > } else if (type == AudioFormat.Encoding.PCM_SIGNED) {
> > linrB.doClick(); signB.doClick();
> > } else if (type == AudioFormat.Encoding.PCM_UNSIGNED) {
> > linrB.doClick(); unsignB.doClick();
> > }
> > float rate = format.getFrameRate();
> > if (rate == 8000) {
> > rate8B.doClick();
> > } else if (rate == 11025) {
> > rate11B.doClick();
> > } else if (rate == 16000) {
> > rate16B.doClick();
> > } else if (rate == 22050) {
> > rate22B.doClick();
> > } else if (rate == 44100) {
> > rate44B.doClick();
> > }
> > switch (format.getSampleSizeInBits()) {
> > case 8 : size8B.doClick(); break;
> > case 16 : size16B.doClick(); break;
> > }
> > if (format.isBigEndian()) {
> > bigB.doClick();
> > } else {
> > litB.doClick();
> > }
> > if (format.getChannels() == 1) {
> > monoB.doClick();
> > } else {
> > sterB.doClick();
> > }
> > }
> > } // End class FormatControls
> >
> >
> > /**
> > * Render a WaveForm.
> > */
> > class SamplingGraph extends JPanel implements Runnable {
> >
> > private Thread thread;
> > private Font font10 = new Font("serif", Font.PLAIN, 10);
> > private Font font12 = new Font("serif", Font.PLAIN, 12);
> > Color jfcBlue = new Color(204, 204, 255);
> > Color pink = new Color(255, 175, 175);
> >
> >
> > public SamplingGraph() {
> > setBackground(new Color(20, 20, 20));
> > }
> >
> >
> > public void createWaveForm(byte[] audioBytes) {
> >
> > lines.removeAllElements(); // clear the old vector
> >
> > AudioFormat format = audioInputStream.getFormat();
> > if (audioBytes == null) {
> > try {
> > audioBytes = new byte[
> > (int) (audioInputStream.getFrameLength()
> > * format.getFrameSize())];
> > audioInputStream.read(audioBytes);
> > } catch (Exception ex) {
> > reportStatus(ex.toString());
> > return;
> > }
> > }
> >
> > Dimension d = getSize();
> > int w = d.width;
> > int h = d.height-15;
> > int[] audioData = null;
> > if (format.getSampleSizeInBits() == 16) {
> > int nlengthInSamples = audioBytes.length / 2;
> > audioData = new int[nlengthInSamples];
> > if (format.isBigEndian()) {
> > for (int i = 0; i < nlengthInSamples; i++) {
> > /* First byte is MSB (high order) */
> > int MSB = (int) audioBytes[2*i];
> > /* Second byte is LSB (low order) */
> > int LSB = (int) audioBytes[2*i+1];
> > audioData[i] = MSB << 8 | (255 & LSB);
> > }
> > } else {
> > for (int i = 0; i < nlengthInSamples; i++) {
> > /* First byte is LSB (low order) */
> > int LSB = (int) audioBytes[2*i];
> > /* Second byte is MSB (high order) */
> > int MSB = (int) audioBytes[2*i+1];
> > audioData[i] = MSB << 8 | (255 & LSB);
> > }
> > }
> > } else if (format.getSampleSizeInBits() == 8) {
> > int nlengthInSamples = audioBytes.length;
> > audioData = new int[nlengthInSamples];
> > if
(format.getEncoding().toString().startsWith("PCM_SIGN"))
> > {
> > for (int i = 0; i < audioBytes.length; i++) {
> > audioData[i] = audioBytes[i];
> > }
> > } else {
> > for (int i = 0; i < audioBytes.length; i++) {
> > audioData[i] = audioBytes[i] - 128;
> > }
> > }
> > }
> >
> > int frames_per_pixel = audioBytes.length /
> > format.getFrameSize()/w;
> > byte my_byte = 0;
> > double y_last = 0;
> > int numChannels = format.getChannels();
> > for (double x = 0; x < w && audioData != null; x++) {
> > int idx = (int) (frames_per_pixel * numChannels * x);
> > if (format.getSampleSizeInBits() == 8) {
> > my_byte = (byte) audioData[idx];
> > } else {
> > my_byte = (byte) (128 * audioData[idx] / 32768 );
> > }
> > double y_new = (double) (h * (128 - my_byte) / 256);
> > lines.add(new Line2D.Double(x, y_last, x, y_new));
> > y_last = y_new;
> > }
> >
> > repaint();
> > }
> >
> >
> > public void paint(Graphics g) {
> >
> > Dimension d = getSize();
> > int w = d.width;
> > int h = d.height;
> > int INFOPAD = 15;
> >
> > Graphics2D g2 = (Graphics2D) g;
> > g2.setBackground(getBackground());
> > g2.clearRect(0, 0, w, h);
> > g2.setColor(Color.white);
> > g2.fillRect(0, h-INFOPAD, w, INFOPAD);
> >
> > if (errStr != null) {
> > g2.setColor(jfcBlue);
> > g2.setFont(new Font("serif", Font.BOLD, 18));
> > g2.drawString("ERROR", 5, 20);
> > AttributedString as = new AttributedString(errStr);
> > as.addAttribute(TextAttribute.FONT, font12, 0,
> > errStr.length());
> > AttributedCharacterIterator aci = as.getIterator();
> > FontRenderContext frc = g2.getFontRenderContext();
> > LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);
> > float x = 5, y = 25;
> > lbm.setPosition(0);
> > while (lbm.getPosition() < errStr.length()) {
> > TextLayout tl = lbm.nextLayout(w-x-5);
> > if (!tl.isLeftToRight()) {
> > x = w - tl.getAdvance();
> > }
> > tl.draw(g2, x, y += tl.getAscent());
> > y += tl.getDescent() + tl.getLeading();
> > }
> > } else if (capture.thread != null) {
> > g2.setColor(Color.black);
> > g2.setFont(font12);
> > g2.drawString("Length: " + String.valueOf(seconds), 3,
h-4);
> > } else {
> > g2.setColor(Color.black);
> > g2.setFont(font12);
> > g2.drawString("File: " + fileName + " Length: " +
> > String.valueOf(duration) + " Position: " + String.valueOf(seconds), 3,
> > h-4);
> >
> > if (audioInputStream != null) {
> > // .. render sampling graph ..
> > g2.setColor(jfcBlue);
> > for (int i = 1; i < lines.size(); i++) {
> > g2.draw((Line2D) lines.get(i));
> > }
> >
> > // .. draw current position ..
> > if (seconds != 0) {
> > double loc = seconds/duration*w;
> > g2.setColor(pink);
> > g2.setStroke(new BasicStroke(3));
> > g2.draw(new Line2D.Double(loc, 0, loc,
> > h-INFOPAD-2));
> > }
> > }
> > }
> > }
> >
> > public void start() {
> > thread = new Thread(this);
> > thread.setName("SamplingGraph");
> > thread.start();
> > seconds = 0;
> > }
> >
> > public void stop() {
> > if (thread != null) {
> > thread.interrupt();
> > }
> > thread = null;
> > }
> >
> > public void run() {
> > seconds = 0;
> > while (thread != null) {
> > if ((playback.line != null) &&
(playback.line.isOpen()) ) {
> >
> > long milliseconds =
> > (long)(playback.line.getMicrosecondPosition() / 1000);
> > seconds = milliseconds / 1000.0;
> > } else if ( (capture.line != null) &&
> > (capture.line.isActive()) ) {
> >
> > long milliseconds =
> > (long)(capture.line.getMicrosecondPosition() / 1000);
> > seconds = milliseconds / 1000.0;
> > }
> >
> > try { thread.sleep(100); } catch (Exception e) {
break; }
> >
> > repaint();
> >
> > while ((capture.line != null &&
!capture.line.isActive()) ||
> > (playback.line != null &&
!playback.line.isOpen()))
> > {
> > try { thread.sleep(10); } catch (Exception e) {
break; }
> > }
> > }
> > seconds = 0;
> > repaint();
> > }
> > } // End class SamplingGraph
> >
> >
> >
> >
> > public static void main(String s[]) {
> > CapturePlayback capturePlayback = new CapturePlayback();
> > capturePlayback.open();
> > JFrame f = new JFrame("Capture/Playback");
> > f.addWindowListener(new WindowAdapter() {
> > public void windowClosing(WindowEvent e) { System.exit(0); }
> > });
> > f.getContentPane().add("Center", capturePlayback);
> > f.pack();
> > Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();
> > int w = 720;
> > int h = 340;
> > f.setLocation(screenSize.width/2 - w/2, screenSize.height/2 -
h/2);
> > f.setSize(w, h);
> > f.show();
> > }
> > }
|
| |
|
| |
 |
Chris Smith

|
Posted: 2006-2-14 22:59:00 |
Top |
java-programmer >> Java Sound
garskof <email***@***.com> wrote:
> I am intersted in building an applet that can both play and record
> sound files. I would like this to work on the widest range of platforms
> (MAC, Linux, WinXP, WinNT, etc) and browsers. What would be the best
> file format for the sound files to accomplish this? Would it be MP3,
> WAV, or what? I am looking to have this work without any added packages
> over and above JDK 1.4.x.
You want the JavaSound API. There's a list of common file types in the
API docs for AudioFileFormat.Type. If I had to guess, I'd say AU format
is safest, since applets are required to be able to play them anyway.
--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
|
| |
|
| |
 |
Roedy Green

|
Posted: 2006-2-15 2:58:00 |
Top |
java-programmer >> Java Sound
On 14 Feb 2006 06:45:49 -0800, "garskof" <email***@***.com> wrote,
quoted or indirectly quoted someone who said :
>I am intersted in building an applet that can both play and record
>sound files
It will have to be a signed Applet.
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
|
| |
|
| |
 |
Roedy Green

|
Posted: 2006-2-15 2:59:00 |
Top |
java-programmer >> Java Sound
On 14 Feb 2006 06:45:49 -0800, "garskof" <email***@***.com> wrote,
quoted or indirectly quoted someone who said :
>I am intersted in building an applet that can both play and record
>sound files. I would like this to work on the widest range of platforms
>(MAC, Linux, WinXP, WinNT, etc) and browsers. What would be the best
>file format for the sound files to accomplish this? Would it be MP3,
>WAV, or what? I am looking to have this work without any added packages
>over and above JDK 1.4.x.
>
>Thanks for any and all info.
see http://mindprod.com/jgloss/sound.html
for your options
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
|
| |
|
| |
 |
| |
 |
Index ‹ java-programmer |
- Next
- 1
- 2
- Newbie question - reading delimited files and printing...Reading files - pipe delimited or comma delimeted...
Searching for a element in one field and then showing certain fields where
element is in line.
eg...
HEHE|HI|ME|2.5
JOKE|HELLO|YOU|3.4
DONT|HI|YOU|3.4
I want all rows with YOU in second column and I want to print out 2nd and
4th columns.
SO, my answer would be
HI 2.5
HI 3.4
...
Next question...
same list only a datestamp on the end...
HEHE|HI|ME|2.5|20031223091234
JOKE|HELLO|YOU|3.4|20031223091245
DONT|HI|YOU|3.4|20031223091247
....
1) I want all rows with YOU in second column and I want to print out 2nd and
4th columns in the 09:00:00 - 09:59:59 time frame.
2) I want an average of response time(4th field).
3) I want an average of response time broken down by hour.
Can someone help with all of this?
Please email to my home email (feel free to copy here).
email***@***.com
take out the _no_spam_
Thanks,
Markis
- 3
- design problem: visitor/multiple dispatch or?Greetings and salutations,
I'm struggling with a bit of a mess (solely created by me and myself).
Suppose a bunch of types (classes) exist, say, T_1, T_2, ... T_n, implementing
a single interface or inheriting from some (abstract) base class T. Also assume
that some 'applicators' exit, say, A_1, A_2 ... Am, all implementing an interface
(or abstract base class) equivalent to --
interface Applicator {
Object apply(T ta, T tb);
}
If both sets T_i and A_j are 'fixed', i.e no new classes T_p nor A_q enter
my messy arena, I could implement all A_i as visitors to the T_j classes
in order to get their job done. OTOH, all T_j classes could double dispatch
the 'A_i.apply' methods to their T_j counterparts to get the job done.
I realise that some form of a Cartesian product of 'apply' methods must
reside somehwere, somehow ...
For the sake of the example, think of the T_j as being subclasses of classes
Short, Int, Long, Double, and let the Appliers be something like 'Add', 'Sub'
etc. i.e. the folllowing code snippet should make sense --
Add myAdd= new Add();
Dbl myDbl= new Dbl(41);
Int myInt= new Int(1);
// assume Num is a superclass of Dbl and Int
Num total= myAdd.apply(myDbl, myInt);
Variable 'total' should have type 'Dbl' in this example. As I wrote above,
there would be no problem if at least set T_j would be fixed; the visitor
pattern would do fine. If set A_i would be fixed the multiple dispatch
pattern (over the set T_j) would be a fine fit. But what to do if both sets
may be expanded?
I've fiddle-diddled with introspection, synthesizing class names given a T_i
and T_j, caching them in hashmaps but to no avail -- my code is a mess and
my design is something I'm ashamed off. I would really appreciate it if
some kind soul here could enlighten me.
TIA, and kind regards,
Jos
- 4
- hi friends.please helpI am trying t make a jTable Using Abstract TableModel. But my JTable
doesnot appear on the frame.I have written two classes myTable and
jTable2 .My code is given below:
import javax.swing.*;
import java.awt.*;
public class myTable {
public static void main(String args[]){
JTable2 tbl2=new JTable2();
JTable aTbl=new JTable(tbl2);
aTbl.updateUI();
aTbl.setVisible(true);
JFrame frame=new JFrame("Jtable using AbstractTableModel");
JPanel pan=new JPanel();
JScrollPane scp=new JScrollPane();
scp.add(aTbl);
pan.add(scp);
frame.getContentPane().add(pan);
frame.setVisible(true);
frame.pack();
}
}
import javax.swing.*;
import java.sql.*;
import java.util.*;
import javax.swing.table.*;
public class JTable2 extends AbstractTableModel{
Connection con;
Statement stmt;
ResultSet rs;
int columns;
Vector allRows;
Vector row=new Vector();
String [] columnNames={"ID_CODE","NAME","SECTION"};
public JTable2(){
// connect to database
try{
db_connect();
getData();
}catch(Exception ex){
ex.printStackTrace();
}
}
void db_connect() throws SQLException{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@158.144.71.242:1521:dbadp","payroll","sush");
System.out.println("Connected");
}catch(Exception ex){
ex.printStackTrace();
}
}
void getData() throws SQLException {
try{
stmt=con.createStatement();
rs=stmt.executeQuery("select idcode,id_name,sec_code from
employee");
ResultSetMetaData rsMetaData=rs.getMetaData();
columns=rsMetaData.getColumnCount();
allRows=new Vector();
while(rs.next()){
Vector newRow=new Vector();
for(int i=1;i<=columns;i++){
newRow.addElement(rs.getObject(i));
}
allRows.addElement(newRow);
}
}catch (Exception ex){
ex.printStackTrace();
}
}
public int getRowCount(){
return allRows.size();
}
public int getColumnCount(){
return columns;
}
public Object getValueAt(int aRow,int aColumn){
row=(Vector) allRows.elementAt(aRow);
return row.elementAt(aColumn);
}
public boolean isCellEditable(int row, int col){
return false;
}
}
- 5
- how to draw ER and UML diagram in eclipse?what free eclipse plugin do you use to draw database ER diagram and
UML diagrams?
I've tried omondo years ago, it leaks memory so bad back then and
always crash my eclipse, is it getting better now?
- 6
- Client application using Weblogic JMS ServerHello, I'm Jose from Barcelona,
I'm not at all expert on JMS, and my question is about how can I
connect a client application running java with a remote JMS Weblogic
Server. I've developed a client program and tested it with a Sun J2EE
server running on a XP box, but the goal is to make it run on an
iSeries machine connecting a WebLogic JMS Server.
My questions are:
Do I have to install some application software on the client box?
Is there any difference between connection with remote JMS servers and
connection with local ones?.
I hope you can help me.
Thank You.
- 7
- Animation ProblemLew wrote:
> James Sarjeant wrote:
>> Thank you so much everyone, it worked with the javax.swing.Timer events.
>> Still got other bugs to iron out but thats a huge hurdle overcome.
>> Thanks again
>
> Remember: you think you have gotten away from the advice about the EDT,
> but you haven't.
>
It's a pesky thing isn't it :-).
--
Knute Johnson
email s/nospam/knute/
- 8
- Debugging API classes in NetbeansWhen Im debugging my program in Netbeans, and I try to debug into API
(e.g. Swing JPanel) the debugger tells me that the source of the class
has not been found in mounted filesystem. Even though
c:\j2sdk1.4.2_02\src.jar is indeed mounted.
How do I debug into API classes?
Thanxxxx,
Barsum
- 9
- drag and drop in a JMenu/JMenuItem
Can someone please point me to some sample code that allows drag and
drop in a JMenu/JMenuItem. I know that Java doesn't support dnd in
the menu stuff, but I need it anyway. Technically speaking it doesn't
have to be a popup menu, but would be nice, as long as it has the look
and feel of a popup menu (i.e. fonts, size, etc.). An example of what
I'm talking about, via menus, is the start menu under Windows. Those
menus allow you to do dnd, but of course it's Windows and they allow
anything and everything. Just to note I'm using JDK 1.5.x if that
helps for the code direction.
- 10
- Thoughts on Code reviewI need some advice guys.. I am proposing that we get someone to do a
complete audit/review of our Java application codebase, about 1000
JSPs/Servlets and 100 EJBs. If I get firms to submit proposals, what
should I be asking /looking out for? I realise that running the
applications through a migration tool will help but I am looking for a
more through analysis of the actual codebase as well as assessment of
the architecture
Thanks
Arvie
- 11
- Check for time functionHello all...I have an issue with one of my java script functions that
I'm hoping someone can easily help with. I have a web based application
that we use to create/sign up for overtime. When we have holidays we
require our employees to sign up in 4 hr increments for the times we
post. I'm having trouble creating a time slot that ends @ 12am. 12pm
and all other hours work fine for start/end times. however 12am causes
problems. My actual script code for this function is below. Someone
help!!!
<SCRIPT language="JavaScript" src="frmvalidation.js"
type="text/JavaScript"></SCRIPT>
<script language="javascript">
function checkValidHoliday(value)
{
if (value=='Y'){
hourblock.style.visibility ='visible';
}
else{
hourblock.style.visibility ='hidden';
}
}
function checkHoliday(frm)
{
if(frm.txtIsHoliday.value=="Y")
{
strFromDt= new Date(frm.txtLimitDate.value);
strToDt= new Date(frm.txtLimitToDate.value);
FromHr=parseInt(frm.txtLimitFrom.value);
FromAMPM=frm.txtLimitFromAM_PM.value;
ToHr=parseInt(frm.txtLimitTo.value);
ToAMPM=frm.txtLimitToAM_PM.value;
if((FromAMPM=="PM") && (FromHr!=12))
FromHr=FromHr+12;
if((ToAMPM=="PM") && (ToHr!=12))
ToHr=ToHr+12;
var fromDt= new
Date(strFromDt.getFullYear(),strFromDt.getMonth(),strFromDt.getDate(),FromHr,0);
var toDt= new
Date(strToDt.getFullYear(),strToDt.getMonth(),strToDt.getDate(),ToHr,0);
//alert(toDt + " " + fromDt);
//alert(FromHr + " " +ToHr);
var HolidayBlock=(parseInt(frm.cboHolidayHours.value) * 360 * 10000)
;
//alert((toDt-fromDt) + " " + HolidayBlock );
if((toDt-fromDt)== HolidayBlock)//14400000)
return true;
else
{
alert("Please select "+ parseInt(frm.cboHolidayHours.value) +" Hour
Block only for Holiday!");
frm.txtLimitFrom.focus();
return false;
}
}
return true;
}
</script>
- 12
- Inidicator Arrow convention for Sort OrderWhich way should an arrow point to indicate an ascending sort or an
ascending list follows?
For an ascending sort the bigger numbers are at the bottom.
So no matter which way you do it, you can misinterpret.
Is there some other less ambiguous convetion to use?
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
- 13
- truncating java doublesHi,
How do you truncate java doubles? I am trying to convert a double to a
number thats rounded to 3 decimal places - i can do this using BigDecimals
easily but cant seem to find anything to do the same with a double.
Thanks
- 14
- Telephonic CredentialsI think it would be nice if I could prove to someone on the other end
of the phone I am me, and demand they prove they are who they claim to
be.
It could be done by letting a modem kick in for a second to exchange
challenge phrases to be encrypted by identification certificate that
might include name, address, phone number, expiry date, company.
Then if some charity I donate to phone me, I can be sure it is them.
There are so many scams out there.
It might also be done by each of us contacting an Internet server.
Has anyone heard of such projects?
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
- 15
- Serializable : readObject and writeObjectHello,
I have 3 classes Personne, entreeb==>FileInputStream ,
sortieb==>FileOutputStream.
The code works one time. The problem is when I add serialized new objects
( launch again the code sortieb) I can't read all objects (entreeb) specific
a new objects added.
have you an idea?
Thanks form help
-----------------------------------------------------------
-----------------------------------------------------------
//Class Personne
import java.io.*;
class Personne implements Serializable {
private String nom;
private int age;
public Personne(String n, int a){
nom = n;
age = a;
}
public void aff() {
System.out.println (nom + " " + age);
}
}
------------------------------------------------
//Flux in
import java.io.*;
import java.util.*;
public class entreeb {
public static void main(String[] args){
Personne p;
int i=0;
try {
FileInputStream fist= new FileInputStream("Personne.ser");
ObjectInputStream oist = new ObjectInputStream(fist);
try {
while (true)
{ System.out.println("i="+i);
p = (Personne) oist.readObject();
p.aff();
i++;
}
} catch (EOFException e) { }
oist.close();
} catch (Exception e) {
System.out.println("Exception loading personne : " + e.getMessage());
}
}
}
------------------------------------------------------------------
//Flux out
import java.io.*;
import java.util.*;
public class sortieb {
public static void main(String[] args) throws IOException {
Personne p = new Personne("name", 55);
File f=new File("Personne.ser");
FileOutputStream fost= new FileOutputStream(f,true);
ObjectOutputStream oost = new ObjectOutputStream(fost);
int i=0;
while (i<5) {
System.out.println("i = "+i+ "p="+p);
oost.writeObject(p);
i+=1;
}
oost.close();
}
}
|
|
|