Re: Java and wav file generation
On 10/6/2011 11:16 AM, Zio Peppe wrote:
Hi folks,
I have a set of binary data of which are known in advance the size
(number of points), the format (32-bit long integers), the sample rate
and the endian (Big or Little).
I would like to build audio files (wav or mp3, doesn't matter for now)
from them with absolutely high fidelity.
I was wondering if there is already a class suitable for such
processing and some example of use.
I had a look on Package javax.sound.sampled, but it is a bit
complicated for a beginner as me :/
Is there a good soul who can show with a bit of code how I can get
success?
Cheers,
ZPP
These might be of some help. They are just snippets used for testing
things but you might be able to make something of it. Post back once
you have better defined what you are up to.
import java.io.*;
import javax.sound.sampled.*;
public class Play {
public static void main(String[] args) {
class MyLineListener implements LineListener {
public void update(LineEvent le) {
LineEvent.Type type = le.getType();
System.out.println(type);
}
};
try {
AudioInputStream fis =
AudioSystem.getAudioInputStream(new File(args[0]));
System.out.println("Input AudioFormat: " + fis.getFormat());
AudioInputStream ais = AudioSystem.getAudioInputStream(
AudioFormat.Encoding.PCM_SIGNED,fis);
AudioFormat af = ais.getFormat();
System.out.println("Output AudioFormat: " + af.toString());
/*
int frameRate = (int)af.getFrameRate();
System.out.println("Frame Rate: " + frameRate);
int frameSize = af.getFrameSize();
System.out.println("Frame Size: " + frameSize);
*/
SourceDataLine line = AudioSystem.getSourceDataLine(af);
line.addLineListener(new MyLineListener());
line.open(af);
int bufSize = line.getBufferSize();
System.out.println("Buffer Size: " + bufSize);
line.start();
byte[] data = new byte[bufSize];
int bytesRead;
while ((bytesRead = ais.read(data,0,data.length)) != -1)
line.write(data,0,bytesRead);
line.drain();
line.stop();
line.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
import java.io.*;
import java.net.*;
import javax.sound.sampled.*;
public class PlayClip {
public static void main(String[] args) {
try {
AudioInputStream ais =
AudioSystem.getAudioInputStream(new File(args[0]));
// AudioSystem.getAudioInputStream(new
URL("http://pscode.org/media/leftright.wav"));
AudioFormat af = ais.getFormat();
Clip line = AudioSystem.getClip();
line.open(ais);
line.start();
Thread.sleep(1);
line.drain();
line.stop();
line.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
import javax.sound.sampled.*;
public class Mixers {
public static void main(String[] args) {
Mixer.Info[] mi = AudioSystem.getMixerInfo();
for (int i=0; i<mi.length; i++)
System.out.println(mi[i].toString());
}
}
/*
* Copyright (c) 2003 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 javax.sound.sampled.*;
public class ListPorts {
public static void main(String[] args) {
Mixer.Info[] aInfos = AudioSystem.getMixerInfo();
for (int i = 0; i < aInfos.length; i++) {
try {
Mixer mixer = AudioSystem.getMixer(aInfos[i]);
mixer.open();
try {
System.out.println(aInfos[i]);
printPorts(mixer, mixer.getSourceLineInfo());
printPorts(mixer, mixer.getTargetLineInfo());
} finally {
mixer.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (aInfos.length == 0) {
System.out.println("[No mixers available]");
}
System.exit(0);
}
public static void printPorts(Mixer mixer, Line.Info[] infos) {
for (int i = 0; i<infos.length; i++) {
try {
if (infos[i] instanceof Port.Info) {
Port.Info info = (Port.Info) infos[i];
System.out.println(" Port "+info);
Port port = (Port) mixer.getLine(info);
port.open();
try {
printControls(port.getControls());
} finally {
port.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void printControls(Control[] controls) {
for (int i = 0; i<controls.length; i++) {
printControl(" ", "Controls["+i+"]: ", controls[i]);
}
if (controls.length == 0) {
System.out.println(" [no controls]");
}
}
static boolean balanceTested = false;
public static void printControl(String indent, String id, Control
control) {
if (control instanceof BooleanControl) {
BooleanControl ctrl = (BooleanControl) control;
System.out.println(indent+id+"BooleanControl: "+ctrl);
//try {
// Thread.sleep(500);
// ctrl.setValue(!ctrl.getValue());
// Thread.sleep(500);
// ctrl.setValue(!ctrl.getValue());
//} catch (Exception e) {}
}
else if (control instanceof CompoundControl) {
CompoundControl ctrl = (CompoundControl) control;
Control[] ctrls = ctrl.getMemberControls();
System.out.println(indent+id+"CompoundControl: "+control);
for (int i=0; i<ctrls.length; i++) {
printControl(indent+" ", "MemberControls["+i+"]: ", ctrls[i]);
}
}
else if (control instanceof EnumControl) {
EnumControl ctrl = (EnumControl) control;
Object[] values = ctrl.getValues();
Object value = ctrl.getValue();
System.out.println(indent+id+"EnumControl: "+control);
for (int i=0; i<values.length; i++) {
if (values[i] instanceof Control) {
printControl(indent+" ", "Values["+i+"]:"+
((values[i]==value)?"*":""), (Control) values[i]);
} else {
System.out.println(indent+" Values["+i+"]:"+
((values[i]==value)?"*":"")+values[i]);
}
}
}
else if (control instanceof FloatControl) {
FloatControl ctrl = (FloatControl) control;
System.out.println(indent+id+"FloatControl: "+ctrl);
//try {
// Thread.sleep(500);
// float x = ctrl.getValue();
// ctrl.setValue((float) (Math.random()*(ctrl.getMaximum() -
// ctrl.getMinimum()) + ctrl.getMinimum())); // Thread.sleep(1000);
// ctrl.setValue(x); //} catch (Exception e) {} //if (ctrl.getType() ==
// FloatControl.Type.BALANCE && !balanceTested) {
// balanceTested = true;
// for (float y = -1.0f; y<=1.0f; y+=0.02) { // ctrl.setValue(y);
// System.out.println(" Set to "+y);
// System.out.println(" res"+ctrl.getValue()); // } //}
} else {
System.out.println(indent+id+"Control: "+control);
}
}
}
package com.knutejohnson.classes;
import java.util.*;
import javax.sound.sampled.*;
public class Tone {
public static float SAMPLE_RATE = 8000f;
public static void sound(int hz, int msecs, double vol)
throws LineUnavailableException {
if (hz <= 0)
throw new IllegalArgumentException("Frequency <= 0 hz");
if (msecs <= 0)
throw new IllegalArgumentException("Duration <= 0 msecs");
if (vol > 1.0 || vol < 0.0)
throw new IllegalArgumentException("Volume out of range 0.0
- 1.0");
byte[] buf = new byte[(int)SAMPLE_RATE * msecs / 1000];
for (int i=0; i<buf.length; i++) {
double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI;
buf[i] = (byte)(Math.sin(angle) * 127.0 * vol);
}
// shape the front and back 10ms of the wave form
for (int i=0; i < SAMPLE_RATE / 100.0 && i < buf.length / 2; i++) {
buf[i] = (byte)(buf[i] * i / (SAMPLE_RATE / 100.0));
buf[buf.length-1-i] =
(byte)(buf[buf.length-1-i] * i / (SAMPLE_RATE / 100.0));
}
AudioFormat af = new AudioFormat(SAMPLE_RATE,8,1,true,false);
SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
sdl.open(af);
sdl.start();
sdl.write(buf,0,buf.length);
sdl.drain();
sdl.close();
}
public static void main(String[] args) throws
LineUnavailableException {
Tone.sound(800,1000,0.8);
}
}
These last two use Java Media Framework, a deprecated API. But it still
works.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.*;
import javax.media.*;
import javax.media.control.*;
import javax.media.format.*;
import javax.media.util.*;
public class VideoPlayer extends Frame {
Player player;
FormatControl formatControl;
FrameGrabbingControl grabber;
public VideoPlayer(String[] args) {
super("Video Player");
setLayout(new BorderLayout());
MenuBar mb = new MenuBar();
setMenuBar(mb);
Menu mfile = new Menu("File");
mb.add(mfile);
final MenuItem mi = new MenuItem("Grab");
mfile.add(mi);
mi.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Buffer buf = grabber.grabFrame();
BufferToImage b2i =
new BufferToImage((VideoFormat)buf.getFormat());
BufferedImage bi = (BufferedImage)b2i.createImage(buf);
if (bi != null) {
try {
ImageIO.write(bi,"JPEG",new File("image.jpg"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
});
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
if (player != null) {
player.stop();
player.close();
System.exit(0);
}
}
});
ControllerListener cl = new ControllerAdapter() {
public void configureComplete(ConfigureCompleteEvent cce) {
System.out.println("configure complete event");
}
public void controllerError(ControllerErrorEvent cee) {
System.out.println("controller error event");
}
public void controllerClosed(ControllerClosedEvent cce) {
System.out.println("controller closed event");
System.exit(0);
}
public void deallocate(DeallocateEvent de) {
System.out.println("deallocate event");
}
public void endOfMedia(EndOfMediaEvent eome) {
System.out.println("end of media event");
}
public void formatChange(FormatChangeEvent fce) {
System.out.println("format change event");
pack();
}
public void internalError(InternalErrorEvent iee) {
System.out.println("internal error");
}
public void mediaTimeSet(MediaTimeSetEvent mtse) {
System.out.println("media time set event");
}
public void prefetchComplete(PrefetchCompleteEvent pce) {
System.out.println("prefetch complete event");
}
public void realizeComplete(RealizeCompleteEvent rce) {
System.out.println("realize complete event");
Component c = player.getVisualComponent();
if (c != null) {
System.out.println(c.getPreferredSize());
add(c,BorderLayout.CENTER);
} else
System.out.println("no visual component");
c = player.getControlPanelComponent();
if (c != null)
add(c,BorderLayout.SOUTH);
formatControl = (FormatControl)
player.getControl("javax.media.control.FormatControl");
if (formatControl != null) {
c = formatControl.getControlComponent();
if (c != null)
add(c,BorderLayout.EAST);
else
System.out.println("no format control component");
} else
System.out.println("no format control");
grabber = (FrameGrabbingControl)player.getControl(
"javax.media.control.FrameGrabbingControl");
if (grabber == null)
mi.setEnabled(false);
pack();
setVisible(true);
}
public void restarting(RestartingEvent re) {
System.out.println("restarting event");
}
public void sizeChange(SizeChangeEvent sce) {
System.out.println("size change event");
}
public void start(StartEvent se) {
System.out.println("start event");
}
public void stop(StopEvent se) {
System.out.println("stop event");
}
public void transition(TransitionEvent te) {
System.out.println("transition event");
int state = te.getCurrentState();
switch (state) {
case Processor.Configuring:
System.out.println(" configuring");
break;
case Processor.Configured:
System.out.println(" configured");
break;
case Processor.Prefetching:
System.out.println(" prefetching");
break;
case Processor.Prefetched:
System.out.println(" prefetched");
break;
case Processor.Realizing:
System.out.println(" realizing");
break;
case Processor.Realized:
System.out.println(" realized");
break;
case Processor.Unrealized:
System.out.println(" unrealized");
break;
case Processor.Started:
System.out.println(" started");
break;
}
}
};
try {
MediaLocator ml;
File file = new File(args[0]);
if (file.exists()) {
ml = new MediaLocator(file.toURI().toURL());
} else
ml = new MediaLocator(args[0]);
// Manager.setHint(Manager.PLUGIN_PLAYER,Boolean.TRUE);
player = Manager.createPlayer(ml);
player.addControllerListener(cl);
player.prefetch();
} catch (NoPlayerException npe) {
System.out.println(npe);
System.exit(0);
} catch (IOException ioe) {
System.out.println(ioe);
System.exit(0);
}
}
public static void main(String[] args) {
new VideoPlayer(args);
}
}
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.media.*;
public class player extends Frame {
Player p;
public player(String[] args) {
try {
setUndecorated(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
p.close();
System.exit(0);
}
});
final MouseListener m = new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
p.close();
System.exit(0);
}
};
ControllerListener cl = new ControllerAdapter() {
public void realizeComplete(RealizeCompleteEvent rce) {
Component comp = p.getVisualComponent();
if (comp != null) {
comp.addMouseListener(m);
add(comp,BorderLayout.CENTER);
}
comp = p.getControlPanelComponent();
add(comp,BorderLayout.SOUTH);
pack();
setVisible(true);
}
};
File f = new File(args[0]);
URL url = null;
if (f.exists())
url = f.toURL();
else
url = new URL(args[0]);
MediaLocator ml = new MediaLocator(url);
p = Manager.createPlayer(ml);
p.addControllerListener(cl);
p.start();
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
}
public static void main(String[] args) {
new player(args);
}
}
--
Knute Johnson