Creating a sound from an array of numeric values and playing it on speakers
How do I create take a sound I have stored as an array (or could be an arraylist if needed) of numeric values (at the moment as doubles) whiten my program and output it to speakers? I am using blueJ.
for example (0, 0.1, 0.4, 0.8, 0.9, 1, 0.8, 0.6, 0.3, 0.1, etc...) would be a very high frequency sin wave.
Edited by: alan2here on Feb 6, 2008 11:28 AM
I stumbled upon this thread with a question somewhat related:
I've recorded a wave file from microphone. But what I would like is an array of numbers in the same way alan said. I'm also working on my own project involving signal processing (i'm trying to do speech recognition).
I can't really find a nice way of getting that array of numbers. I've tried to find out how wave file stores it's data, and directly read from the File object, but i figured there should be an easier way...
I used this code to read the sound:
* SimpleAudioRecorder.java
* This file is part of jsresources.org
* Copyright (c) 1999 - 2003 by Matthias Pfisterer
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
|<--- this code is formatted to fit into 80 columns --->|
import java.io.IOException;
import java.io.File;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.AudioFileFormat;
public class SimpleAudioRecorder
extends Thread
private TargetDataLine m_line;
private AudioFileFormat.Type m_targetType;
private AudioInputStream m_audioInputStream;
private File m_outputFile;
public SimpleAudioRecorder(TargetDataLine line,
AudioFileFormat.Type targetType,
File file)
m_line = line;
m_audioInputStream = new AudioInputStream(line);
m_targetType = targetType;
m_outputFile = file;
/** Starts the recording.
To accomplish this, (i) the line is started and (ii) the
thread is started.
public void start()
/* Starting the TargetDataLine. It tells the line that
we now want to read data from it. If this method
isn't called, we won't
be able to read data from the line at all.
m_line.start();
/* Starting the thread. This call results in the
method 'run()' (see below) being called. There, the
data is actually read from the line.
super.start();
/** Stops the recording.
Note that stopping the thread explicitely is not necessary. Once
no more data can be read from the TargetDataLine, no more data
be read from our AudioInputStream. And if there is no more
data from the AudioInputStream, the method 'AudioSystem.write()'
(called in 'run()' returns. Returning from 'AudioSystem.write()'
is followed by returning from 'run()', and thus, the thread
is terminated automatically.
It's not a good idea to call this method just 'stop()'
because stop() is a (deprecated) method of the class 'Thread'.
And we don't want to override this method.
public void stopRecording()
m_line.stop();
m_line.close();
/** Main working method.
You may be surprised that here, just 'AudioSystem.write()' is
called. But internally, it works like this: AudioSystem.write()
contains a loop that is trying to read from the passed
AudioInputStream. Since we have a special AudioInputStream
that gets its data from a TargetDataLine, reading from the
AudioInputStream leads to reading from the TargetDataLine. The
data read this way is then written to the passed File. Before
writing of audio data starts, a header is written according
to the desired audio file type. Reading continues untill no
more data can be read from the AudioInputStream. In our case,
this happens if no more data can be read from the TargetDataLine.
This, in turn, happens if the TargetDataLine is stopped or closed
(which implies stopping). (Also see the comment above.) Then,
the file is closed and 'AudioSystem.write()' returns.
public void run()
try
AudioSystem.write(
m_audioInputStream,
m_targetType,
m_outputFile);
catch (IOException e)
e.printStackTrace();
public static void main(String[] args)
if (args.length != 1 || args[0].equals("-h"))
printUsageAndExit();
/* We have made shure that there is only one command line
argument. This is taken as the filename of the soundfile
to store to.
String strFilename = args[0];
File outputFile = new File(strFilename);
/* For simplicity, the audio data format used for recording
is hardcoded here. We use PCM 44.1 kHz, 16 bit signed,
stereo.
AudioFormat audioFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
44100.0F, 16, 2, 4, 44100.0F, false);
/* Now, we are trying to get a TargetDataLine. The
TargetDataLine is used later to read audio data from it.
If requesting the line was successful, we are opening
it (important!).
DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat);
TargetDataLine targetDataLine = null;
try
targetDataLine = (TargetDataLine) AudioSystem.getLine(info);
targetDataLine.open(audioFormat);
catch (LineUnavailableException e)
out("unable to get a recording line");
e.printStackTrace();
System.exit(1);
/* Again for simplicity, we've hardcoded the audio file
type, too.
AudioFileFormat.Type targetType = AudioFileFormat.Type.WAVE;
/* Now, we are creating an SimpleAudioRecorder object. It
contains the logic of starting and stopping the
recording, reading audio data from the TargetDataLine
and writing the data to a file.
SimpleAudioRecorder recorder = new SimpleAudioRecorder(
targetDataLine,
targetType,
outputFile);
/* We are waiting for the user to press ENTER to
start the recording. (You might find it
inconvenient if recording starts immediately.)
out("Press ENTER to start the recording.");
try
System.in.read();
catch (IOException e)
e.printStackTrace();
/* Here, the recording is actually started.
recorder.start();
out("Recording...");
/* And now, we are waiting again for the user to press ENTER,
this time to signal that the recording should be stopped.
out("Press ENTER to stop the recording.");
try
System.in.read();
catch (IOException e)
e.printStackTrace();
/* Here, the recording is actually stopped.
recorder.stopRecording();
out("Recording stopped.");
private static void printUsageAndExit()
out("SimpleAudioRecorder: usage:");
out("\tjava SimpleAudioRecorder -h");
out("\tjava SimpleAudioRecorder <audiofile>");
System.exit(0);
private static void out(String strMessage)
System.out.println(strMessage);
}Daniel
Similar Messages
-
How to create PNG file from byte array of RGB value?
Hi
Here is my problem.
I have drawn some sketchs (through code in runtime) on canvas. I have grabbed the RGB information for the drwan image and converted to byte array.
I have to pass this byte array to server and generate a png file and save.
Please help.{color:#ff0000}Cross posted{color}
http://forum.java.sun.com/thread.jspa?threadID=5218093
{color:#000080}Cross posting is rude.
db{color} -
My macbook doesn't work. After pressing down the power button I hear the sound from starting the apple symbol appears and after a while a sign prohibited appears on the place of the apple symbol
Hi Kappy Thanks for your answer. I did a reboot on my Macbook as suggested and this operation is going on non stop for 14 hours and on the screen always appears the same message that you can see in the picture in attachment. Any ideas?
-
I need to create a image using some numeric values and i want to display values in image,
I need to create a image using some numeric values and i want to display values in image, Numeric values be enterd by text file, excel file or user input by dialog box,
this is the sample if image.
http://s17.postimg.org/5xvtzbztn/5_01_03_I.png
128 x 16 Pixels , Back ground Black, Numbers in Red, Should be same as above picture.
Because i have hundreds of images to create like this.
If any one can make a script for this it is very good.
Sorry about my English.
Thank you.Have you checked out data driven graphics?
https://helpx.adobe.com/photoshop/using/creating-data-driven-graphics.html -
Numeric value and scientific notation
Hi,
with Oracle 8 or 10, the query (via TOAD or my app : Delphi + BDE)
SELECT 0.0008 FROM DUAL returns 0.0008,
but the query
SELECT 0.00008 FROM DUAL returns 8E-5.
Is there a way to avoid this display in scientific notation, except changing all my queries ? Or to push the limit for this display one digit later ?
Maybe with an Oracle parameter ?
Thanks for your help !duplicate for thread
numeric value and scientific notation -
I have a iPhone 4S and when watching videos on the internet sound cuts out as the video is playing. The rest of the video plays with no sound. Sometimes when I pause It and play again sound comes back but not all the time. can anyone help?
The "restore disk" is built into the Mac. See About Recovery.
Need more specifics about what error messages you got while installing Adobe Flash.
However, you can almost avoid Flash altogether by setting YouTube to play the HTML5 version instead.
Click the Try something new! link at the bottom of the YouTube page.
I don't know about the sound issue. Might be hardware as you think. Try other headphones to check. -
Limiting entry in a JTextField to numeric value and "%" value
Hi,
I want to allow the user to enter numeric value and % value
How can I limit the user to make such a entry in JTextFieldUse the code given below to make your textfield accept only numeric values. You can modify itto include % values too.
textField.setDocument( new TextFieldVerifier() );
class TextFieldVerifier extends PlainDocument {
public void insertString( int offset, String str, AttributeSet attSet ) throws BadLocationException {
boolean valid = false;
if ( str == null ) {
return;
String old = getText( 0, getLength() );
/* insert the new string at the given offset, into the old string */
String newStr = old.substring( 0, offset ) + str + old.substring( offset );
try {
/* check if the new string is a valid integer */
Integer.parseInt( newStr );
valid = true;
} catch ( NumberFormatException ne ) {
/* invalid, if not an integer */
valid = false;
Toolkit.getDefaultToolkit().beep();
if ( valid ) {
super.insertString( offset, str, attSet );
} -
Create an image from float array?
Dear All,
I have a float array containing pixel values. From that array I want to create an image (let's say in JPEG format).
How should I do that?
thanksHi musti168,
You're going through your entire image pixel-by-pixel and getting each of their values - why don't you just use the IMAQ ImageToArray function?
On this forum post I found an example of IMAQ ArrayToImage: http://forums.ni.com/t5/LabVIEW/IMAQ-arraytoimage-example/td-p/68418
You can use some of the IMAQ Image Processing palette to change the image to gray scale - possibly a threshold.
Julian R.
Applications Engineer
National Instruments -
Create Class objects from an Array of File Objects
Hi There,
I'm having extreme difficulty in trying to convert an array of file objects to Class objects. My problem is as follows: I'm using Jfilechooser to select a directory and get an array of files of which are all .class files. I want to create Class objects from these .class files. Therefore, i can extract all the constructor, method and field information. I eventually want this class information to display in a JTree. Very similar to the explorer used in Netbeans. I've already created some code below, but it seems to be throwing a NoSuchMethodError exception. Can anyone please help??
Thanks in advance,
Vikash
/* the following is the class im using */
class FileClassLoader extends ClassLoader {
private File file;
public FileClassLoader (File ff) {
this.file = ff;
protected synchronized Class loadClass() throws ClassNotFoundException {
Class c = null;
try {
// Get size of class file
int size = (int)file.length();
// Reserve space to read
byte buff[] = new byte[size];
// Get stream to read from
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream (fis);
// Read in data
dis.readFully (buff);
// close stream
dis.close();
// get class name and remove ".class"
String classname = null;
String filename = file.getName();
int i = filename.lastIndexOf('.');
if(i>0 && i<filename.length()-1) {
classname = filename.substring(0,i);
// create class object from bytes
c = defineClass (classname, buff, 0, buff.length);
resolveClass (c);
} catch (java.io.IOException e) {
e.printStackTrace();
return c;
} // end of method loadClass
} // end of class FileClassLoader
/* The above class is used in the following button action in my gui */
/* At the moment im trying to output the data to standard output */
private void SelectPackage_but2ActionPerformed(java.awt.event.ActionEvent evt) {
final JFileChooser f = new JFileChooser();
f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int rVal = f.showOpenDialog(Remedy.this);
// selects directory
File dir = f.getSelectedFile();
// gets a list of files within the directory
File[] allfiles = dir.listFiles();
// for loop to filter out all the .class files
for (int k=0; k < allfiles.length; k++) {
if (allfiles[k].getName().endsWith(".class")) {
try {
System.out.println("File name: " + allfiles[k].getName()); // used for debugging
FileClassLoader loader = new FileClassLoader(allfiles[k]);
Class cl = loader.loadClass();
//Class cl = null;
Class[] interfaces = cl.getInterfaces();
java.lang.reflect.Method[] methods = cl.getDeclaredMethods();
java.lang.reflect.Field[] fields = cl.getDeclaredFields();
System.out.println("Class Name: " + cl.getName());
//print out methods
for (int m=0; m < methods.length; m++) {
System.out.println("Method: " + methods[m].getName());
// print out fields
for (int fld=0; fld < fields.length; fld++) {
System.out.println("Field: " + fields[fld].getName());
} catch (Exception e) {
e.printStackTrace();
} // end of if loop
} // end of for loop
packageName2.setText(dir.getPath());
}It's throwing the exeption on the line:
FileClassLoader loader = new FileClassLoader(allfiles[k]);
I'm sure its something to do with the extended class i've created. but i cant seem to figure it out..
Thanks if you can figure it out -
Imageicon created from byte array gives -1 height and -1 width...
Hi,
when I am trying to create an imageicon object from byte arrays the length and width of the object are coming to be -1.So I am unable to resize the image..
This is happening for only few images, most of them are working fine and I can resize it...
What possibly could be wrong??
ImageIcon imageIcon = new ImageIcon(pImageData) where pImageData is bytearray..
but I am getting imageIcon.getIconWidth()=-1
and
imageIcon.getIconHeight()=-1
Can anyone help???es5f2000 wrote:
I'm not sure if this is related, but I believe that images which are not currently being rendered return -1, -1 as their size.It is not even correct, so I'm confident it is not related.
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.imageio.ImageIO;
import java.net.URL;
class TestIconSize {
public static void main(String[] args) throws Exception {
Image image = ImageIO.read( new URL(
"http://forums.sun.com/im/silver-star.gif") );
ImageIcon imageIcon = new ImageIcon( image );
System.out.println( "Width: " + imageIcon.getIconWidth() );
System.out.println( "Height: " + imageIcon.getIconHeight() );
}Output.
andrew@pc1:/media/disk/projects/numbered/all$ java TestIconSize
Width: 16
Height: 16
andrew@pc1:/media/disk/projects/numbered/all$ The post after yours seems of even more dubious quality. For those (and other) reasons, I second Darryl's call for an SSCCE. -
Creating a String from an array of characters.
Hi,
i'm trying to make a string from an array of characters, this i've managed:
char data[] = new char[x];
String str = new String(data);My problem is this: Let's say the array of characters has space for 10 chars, but i only input 5, when i convert it to a string, the 5 characters show up fine, but the last remaining characters show up as little boxes ( [] [] [] [] [] ) .
It there a way to remove these?
Thanks in advance
Mikejverd wrote:
georgemc wrote:
String str = new String(data).trim();
Does the null character count as whitespace?Seems to. Actually, I'm getting different results depending on the compiler used.
public static void main(String[] args) {
char[] c = new char[10];
for(int i = 0; i < 5; i++) {
c[i] = (char) ('a' + i);
String first = new String(c);
System.err.println("[" + first + "]");
System.err.println(first.length());
String second = new String(c).trim();
System.err.println("[" + second + "]");
System.err.println(second.length());
}ECJ-compiled output:
>
[abcde
10
[abcde]
5
>
javac-compiled output:
>
[abcde]
10
[abcde]
5
>
Odd -
Displaying a picture from an array of pixel values
I have a picture I want to display in an AWT frame. The picture is stored as several arrays of pixel values which represent rectangles.
Each rectangle has a start co-ordinate and a height and width.
There is a ColorModel associated with the pixel values, so that's not a problem.
What's the best way to display these rectangles as pixels, and patch them all together to make the full picture? I'm currently trying to use a MemoryImageSource, but I'm having trouble displaying more than one rectangle at once, and the picture flickers like mad, suggesting MemoryImageSource intended for animation, whereas I just want to display the picture once.
Any suggestions?OK, that looks good. I'm investigating it.
However, It's not clear how to get the pixel values from an array into it. It requires a WriteableRaster of the pixel data, and to create a WriteableRaster, you need a DataBuffer... which is Abstract!
Do you know how to make a DataBuffer from an array? -
No sound from Apogee Jam with iPad mini and Lightning-30 pin adapter
Hello everybody.
I'm trying to use my Apogee Jam with iPad mini but I am unable to hear any sound from it. Jam seems to work, since the led become green and react to the guitar signal. I tried two different guitars and different cables but nothing changes. Jam also works perfectly on MacBook Pro and garage Band, so I first assumed the issue was in the iPad or in the Lightning-30 pin adapter (genuine).
Oddly on AmpliTube I can tune the guitar, so some signal arrives to the iPad, but I can't do the same on JamUp, where the tuner seems not to reiceve any signal. Are there some settings I should check on the apps?
Thanks for any suggestions!Make sure you have the monitor input turned on in GarageBand. http://youtu.be/Eb8bN3tExio
-
Hi I have a problem with my iPhone 4S I have no sound from my speaker , keyboard, notifications. or volume controls, I have reset my iphone many times and still the same, any advise will be greatful
ThanksI don't think that a software update from Apple will solve the issues that you are having. You have a rogue installation. After you posted I have just done the following:
Disk Utility can verify my partitioned Volume (including my boot disk) AND REPAIR the non-boot disks on the same Volume without a glitch. It repairs the non-boot disks containing data smoothly.
I have used Mail to send some mails from some Yahoo and Hotmail accounts to my Thunderbird client containing GMail accounts - absolutely normal.
I have iLife '09 but my iMovie '09 and iPhoto '09 open in a jiffy and I see no issues here. I have 6GB RAM (Maximum) on an early 2008 Macbook Pro with a 750GB hard drive partitioned with 120GB reserved for the Boot Drive.
I am sorry that I cannot help further but I am sure there must be a way to reinstall the software without having to revert to restoring your ML backup. I have two clones and if you have such I would attempt to do that through that rather than through Time Machine - that is of course if you have a cloned drive.
Good luck! -
Store an encrypted numeric value and make the unencrypted value visible to just some users in Apex
I'm looking for a way to store an encypted numeric value in one field in a table (so that it appears encrypted even to a DBA) and to display the unencypted value in Apex forms and interactive reports for some users but not others.
Any suggestions as to how I could achieve this?
Thanks in advance.
MartinTry these documents:
Using Column Masking to Display Sensitive Columns as NULL Values
Using VPD in an APEX Application
Securing Stored Data Using Transparent Data Encryption
The features you request are Database Features.
You could use DBMS_CRYPTO for data encryption instead of TDE, but you will have to create a package for your insert,update, deletes along with a view that allows decryption based on v('APP_USER').
Also, you won't be able to search on that column if you use DBMS_CRYPTO.
Maybe you are looking for
-
Permissions on an external hard drive
Can someone PLEASE help. I have two external hard drives that when I plug into my MacBook come up as read only. I have tried to use the Get Info and change the Ownership & Permissions settings, but there is no options, it just tells me I can read onl
-
Accounts payable invoices (fv50) - duplicate invoices hard warning
Currently we only receive a soft warning when we try to enter a duplicate invoice. Is there a way to reconfigure to make the warning a hard warning that can be overwritten it necessary. We are running ECC 6.0. Thanks, Jon
-
GetDocAttribute() issue
I've tried to use the XPath method getDocAttribute("filename") to get the original name of an attachment (receive mail action) without success. I've also tried "name" and "file" but it didn't work either. Finally I found out, that content-type (getCo
-
Please refer to my pic below: example, i do have one switch, with all LAN ports (1Gbps) and my wireless ap, connected to this one of the port Q1 Let say my wireless ap, can support up to 54mbps, and how much speed for each clients if 1. only 1 use
-
Sync Apps is disabled in my iTunes
Sync Apps is disabled in my iTunes. How to make it enable and sync my apps to iphone.