can anybody tell me why the following code doesn't work properly?
I want to play and stop an audio file.
I can do the playback but whenever I click the stop button nothing happens.
Here's the code :
Thank you.
..................
import java.io.*;
import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.event.*;
public class SoundClipTest extends JFrame {
final JButton button1 = new JButton("Play");
final JButton button2 = new JButton("Stop");
int stopPlayback = 0;
// Constructor
public SoundClipTest() {
button1.setEnabled(true);
button2.setEnabled(false);
// button play
button1.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
button1.setEnabled(false);
button2.setEnabled(true);
play();
}// end actionPerformed
}// end ActionListener
);// end addActionListener()
// button stop
button2.addActionListener(
new ActionListener() {
public void actionPerformed(
ActionEvent e) {
//Terminate playback before EOF
stopPlayback = 1;
}//end actionPerformed
}//end ActionListener
);//end addActionListener()
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Test Sound Clip");
this.setSize(300, 200);
JToolBar bar = new JToolBar();
bar.add(button1);
bar.add(button2);
bar.setOrientation(JToolBar.VERTICAL);
add("North", bar);
add("West", bar);
setVisible(true);
}
void play() {
try {
final File inputAudio = new File("first.wav");
// First, we get the format of the input file
final AudioFileFormat.Type fileType =
AudioSystem.getAudioFileFormat(inputAudio).getType();
// Then, we get a clip for playing the audio.
final Clip c = AudioSystem.getClip();
// We get a stream for playing the input file.
AudioInputStream ais = AudioSystem.getAudioInputStream(inputAudio);
// We use the clip to open (but not start) the input stream
c.open(ais);
// We get the format of the audio codec
// (not the file format we got above)
final AudioFormat audioFormat = ais.getFormat();
c.start();
if (stopPlayback == 1) {
c.stop();
}
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}// end play
public static void main(String[] args) {
//new SoundClipTest().play();
new SoundClipTest();
}
}
your if (stopPlayback == 1 ) will only be run once -- you'll have to enclose it in a while(true) loop to make sure it keeps being evaluated, make sure you add a pause as well otherwise you will burn a lot of unnecessary cycles.
Update: I was assuming you ran a second thread to watch on the stopPlayback value - I now see this is not the case. Why don't you just call the c.stop() from your ActionListener?
Related
I'm new to programming and I couldnt figure out how to play a sound clip. The code run smoothly but there is no sound coming out from intellij.
Here's my code
package ProjectWumpus;
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
public class testClass {
public static void main(String[] args) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
File file = new File("C:\\Users\\Correct_Answer_Sound_Effect.wav");
AudioInputStream audiostream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audiostream);
clip.start();
My audio from my pc is working fine.
In the comments, both respondents pointed out that the program closes before the Clip has a chance to play. Clips immediately return control back to the main thread. The code which executes the playback is on a daemon thread. Daemon threads will not hold open a program that is ready to close.
FWIW, Here is perhaps a better way to test. In the following code a simple GUI: a button that plays the sound. This is a more typical of how clips are used.
public class TestClip {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run()
{
DemoFrame frame = new DemoFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class DemoFrame extends JFrame {
private static final long serialVersionUID = 1L;
private Clip clip;
public DemoFrame() {
setSize(300, 100);
JPanel panel = new JPanel();
JButton button = new JButton("Play clip");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clip.setFramePosition(0);
clip.start();
}
});
panel.add(button);
add(panel);
// Set up the Clip
URL url = this.getClass().getResource("mySound.wav");
try {
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
clip = AudioSystem.getClip();
clip.open(ais);
} catch ( LineUnavailableException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
I recommend using URL over File for the getAudioInputStream method. In this case, it's assumed the audio resource is in the same directory as the class that is calling it. A URL has the benefit of working when the class is packaged in a jar (unlike File).
I can't figure out how to call this class and make it execute. I am calling methods from other classes to make a menu to take it to different related tasks as lesson on Mexico, but I can't figure out how to make it display this class. in the different cases each call a method that executes it. i want to do this for the second program i posted. I want to make it execute th program so it can play its song
Main Class:
import javax.swing.JOptionPane;
public class MexicoProject
{
public static void main(String[] args)
{
String[] choice = {"History", "Trivia", "Intro", "Anthem", "Quit"};
String Menu;
do
{
Menu = (String)JOptionPane.showInputDialog(null, "Welcome, this program will teach you about the history of Mexico.\nPick one of the options below.",
"Mexico History", JOptionPane.QUESTION_MESSAGE, null, choice, choice[0]);
if (Menu == null)
JOptionPane.showMessageDialog(null, "Pick something!");
else
{
switch (Menu)
{
case "History":
MexicoHistory.History();
break;
case "Trivia":
Quiz();
break;
case "Intro":
FrenchIntro.Intro();
break;
case "Anthem":
{
break;
}
break;
case "Quit":
JOptionPane.showMessageDialog(null, "Goodbye!");
break;
default:
JOptionPane.showMessageDialog(null, "Something went wrong! Try again!");
}
}
} while (Menu != "Quit");
}
Class Being Called:
import java.awt.event.*;
import java.io.*;
import javax.sound.sampled.*;
public class Song extends JFrame
{
AudioFormat audioFormat;
AudioInputStream audioInputStream;
SourceDataLine sourceDataLine;
boolean stopPlayback = false;
final JButton stopBtn = new JButton("Stop");
final JButton playBtn = new JButton("Play");
final JTextField textField = new JTextField("MexicanNationalAnthem.wav");
public static void main(String args[])
{
new Song();
}//end main
//-------------------------------------------//
public Song() //constructor
{
stopBtn.setEnabled(false);
playBtn.setEnabled(true);
//Instantiate and register action listeners
// on the Play and Stop buttons.
playBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
stopBtn.setEnabled(true);
playBtn.setEnabled(false);
playAudio();//Play the file
}//end actionPerformed
}//end ActionListener
);//end addActionListener()
stopBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Terminate playback before EOF
stopPlayback = true;
}//end actionPerformed
}//end ActionListener
);//end addActionListener()
getContentPane().add(playBtn,"West");
getContentPane().add(stopBtn,"East");
getContentPane().add(textField,"North");
setTitle("Himno Nacional Mexicano");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(250,70);
setVisible(true);
}//end constructor
//-------------------------------------------//
//This method plays back audio data from an
// audio file whose name is specified in the
// text field.
public void playAudio()
{
try
{
File soundFile = new File(textField.getText());
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
audioFormat = audioInputStream.getFormat();
System.out.println(audioFormat);
DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class,audioFormat);
sourceDataLine =(SourceDataLine)AudioSystem.getLine(dataLineInfo);
//Create a thread to play back the data and
// start it running. It will run until the
// end of file, or the Stop button is
// clicked, whichever occurs first.
// Because of the data buffers involved,
// there will normally be a delay between
// the click on the Stop button and the
// actual termination of playback.
new PlayThread().start();//call the PlayThread class
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}//end catch
}//end playAudio
//=============================================//
//Inner class to play back the data from the
// audio file.
class PlayThread extends Thread
{
byte tempBuffer[] = new byte[10000];
public void run()
{
try
{
sourceDataLine.open(audioFormat);
sourceDataLine.start();
int cnt;
//Keep looping until the input read method
// returns -1 for empty stream or the
// user clicks the Stop button causing
// stopPlayback to switch from false to
// true.
while((cnt = audioInputStream.read(tempBuffer,0,tempBuffer.length)) != -1&& stopPlayback == false)
{
if(cnt > 0)
{
//Write data to the internal buffer of
// the data line where it will be
// delivered to the speaker.
sourceDataLine.write(tempBuffer, 0, cnt);
}//end if
}//end while
//Block and wait for internal buffer of the
// data line to empty.
sourceDataLine.drain();
sourceDataLine.close();
//Prepare to playback another file
stopBtn.setEnabled(false);
playBtn.setEnabled(true);
stopPlayback = false;
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}//end catch
}//end run
}//end inner class PlayThread
}//===================================//
Make sure that all the classes remain in same package.
You can call the method of other classes by creating a object for class being called ..
then use the object to call the method name..
classbeingcalled obj= new classbeingcalled();
obj.methodname();
or declare your method as a static method so you can call the method by using the class name
public static returntype methodname(){
...
}
from any class in the package
classname.methodname();
PS: If you are not satisfied with this answer or dint expect this answer please be clear with your question.
this is the first time for me that I try to use a song within my code.
I have been following a webpage which explains how to play songs (http://www3.ntu.edu.sg/home/ehchua/programming/java/J8c_PlayingSound.html), but I run into the error ava.lang.IllegalArgumentException: Invalid format.
I don't understand why this happens and what I could do to play a song.
This is the code that doesn't work:
private void startMusic() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
// from a wave File
File soundFile = new File("/home/simone/OhHa/Pakman02/src/main/java/Pakman/ArsenioLupin.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
// For small-size file only. Do not use this to open a large file over slow network, as it blocks.
// start()
clip.start(); // play once
// Loop()
// clip.loop(0); // repeat none (play once), can be used in place of start().
// clip.loop(5); // repeat 5 times (play 6 times)
clip.loop(Clip.LOOP_CONTINUOUSLY); // repeat forever
}
Any suggestions?
try this. note the import of the javax.sound.sampled.*
import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
import javax.swing.*;
public class SoundClipTest extends JFrame {
// Constructor
public SoundClipTest() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Test Sound Clip");
this.setSize(300, 200);
this.setVisible(true);
try {
// Open an audio input stream.
URL url = this.getClass().getClassLoader().getResource("/home/simone/OhHa/Pakman02/src/main/java/Pakman/ArsenioLupin.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new SoundClipTest();
}
}
an alternative is
import javax.swing.*;
import sun.audio.*;
import java.awt.event.*;
import java.io.*;
public class Sound {
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(200,200);
JButton button = new JButton("Click me");
frame.add(button);
button.addActionListener(new AL());
frame.show(true);
}
public static class AL implements ActionListener{
public final void actionPerformed(ActionEvent e){
music();
}
}
public static void music(){
AudioPlayer MGP = AudioPlayer.player;
AudioStream BGM;
AudioData MD;
ContinuousAudioDataStream loop = null;
try{
BGM = new AudioStream(new FileInputStream("C:\home\simone\OhHa\Pakman02\src\main\java\Pakman\ArsenioLupin.wav"));
MD = BGM.getData();
loop = new ContinuousAudioDataStream(MD);
}catch(IOException error){
System.out.print("file not found");
}
MGP.start(loop);
}
}
I am using this mmscomputing library as java applet to scan an image or document.
Using swings,awt i created one scan button which is acquiring scanner by calling scanner.acquire() method of mmscomputing jar..
and then placing that scanned image into jpanel for displaying.
Problem is, first time when i start my applet and hitting my scan button..scanning works fine..Twain states it goes into are: 3,4,5,6,7,5,4,3
then second time,hitting my scan button again ..
Twain states it goes into are: 3,4,5,4,3
It's not going into image transfer ready and transferring state and thus not into below CODE IF loop
if (type.equals(ScannerIOMetadata.ACQUIRED))
so i am not able to see the new scanned image into my jpanel second time...
then third time, hitting my scan button .. again it works fine.. getting into all states.
So i mean, For alternatively turns or restarting the java applet again ..it works.
what would be the issue.. ?
I want, every time when i hit scan button it should get me a new image into Jpanel.. but it's doing alternative times.
can i forcefully explicitly set or change twain states to come into 6th and 7th states..
or is there some twain source initialisation problem occurs second time?
because restarting applet is doing fine every time.. or some way to reinitialise applet objects everytime on clicking scan button..as it would feel like I am restarting applet everytime on clicking scan button...
I am not getting it..
Below is the sample code:
import uk.co.mmscomputing.device.twain.TwainConstants;
import uk.co.mmscomputing.device.twain.TwainIOMetadata;
import uk.co.mmscomputing.device.twain.TwainSource;
import uk.co.mmscomputing.device.twain.TwainSourceManager;
public class XXCrop extends JApplet implements PlugIn, ScannerListener
{
private JToolBar jtoolbar = new JToolBar("Toolbar", JToolBar.HORIZONTAL);
ImagePanel ipanel;
Image im =null;
BufferedImage imageforCrop;
ImagePlus imp=null;
int imageWidth;
int imageHeight;
private static final long serialVersionUID = 1L;
Container content = null;
private JPanel jContentPane = null;
private JButton jButton = null;
private JButton jButton1 = null;
JCheckBox clipBox = null;
JPanel crpdpanel=null;
JPanel cpanel=null;
private Scanner scanner=null;
private TwainSource ts ;
private boolean is20;
ImagePanel imagePanel,imagePanel2 ;
public static void main(String[] args) {
new XXCrop().setVisible(true);
}
public void run(String arg0) {
new XXCrop().setVisible(false);
repaint();
}
/**
* This is the default constructor
*/
public XXCrop() {
super();
init();
try {
scanner = Scanner.getDevice();
if(scanner!=null)
{
scanner.addListener(this);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
/**
* This method initializes this
*
* #return void
*/
public void init()
{
this.setSize(1200, 600);
this.setLayout(null);
//this.revalidate();
this.setContentPane(getJContentPane());
}
private JToolBar getJToolBar()
{
jtoolbar.add(getJButton1());
jtoolbar.add(getJButton());
jtoolbar.setName("My Toolbar");
jtoolbar.addSeparator();
Rectangle r=new Rectangle(0, 0,1024, 30 );
jtoolbar.setBounds(r);
return jtoolbar;
}
private JPanel getJContentPane()
{
if (jContentPane == null)
{
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(getJToolBar());
}
return jContentPane;
}
private JButton getJButton() {
if (jButton == null) {
jButton = new JButton();
jButton.setBounds(new Rectangle(4, 16, 131, 42));
jButton.setText("Select Device");
jButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (scanner.isBusy() == false) {
selectDevice();
}
}
});
}
return jButton;
}
/* Select the twain source! */
public void selectDevice() {
try {
scanner.select();
} catch (ScannerIOException e1) {
IJ.error(e1.toString());
}
}
private JButton getJButton1()
{
if (jButton1 == null) {
jButton1 = new JButton();
jButton1.setBounds(new Rectangle(35,0, 30, 30));
jButton1.setText("Scan");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e)
{//jContentPane.remove(crpdpanel);
//jContentPane.removeAll();
//jContentPane.repaint();
//jContentPane.revalidate();
getScan();
}
});
}
return jButton1;
}
public void getScan()
{
try
{
//scanner = Scanner.getDevice();
//scanner.addListener(this);
scanner.acquire();
}
catch (ScannerIOException e1)
{
IJ.showMessage("Access denied! \nTwain dialog maybe already opened!");
e1.printStackTrace();
}
}
public Image getImage()
{
Image image = imp.getImage();
return image;
}
/*Image cimg;
public Image getCimg()
{
return cimg;
}*/
public void update(ScannerIOMetadata.Type type, ScannerIOMetadata metadata) {
if (type.equals(ScannerIOMetadata.ACQUIRED))
{
//imagePanel.revalidate();
//imagePanel.repaint();
//imagePanel.invalidate();
//jContentPane.remove(ipanel);
//ipanel.repaint();
if(imp!=null)
{
jContentPane.remove(ipanel);
jContentPane.remove(cpanel);
jContentPane.remove(crpdpanel);
}
imp = new ImagePlus("Scan", metadata.getImage());
//imp.show();
im = imp.getImage();
//imagePanel = new ImagePanel(im,imageWidth,imageHeight);
imagePanel = new ImagePanel(im);
imagePanel.updateUI();
imagePanel.repaint();
imagePanel.revalidate();
ClipMover mover = new ClipMover(imagePanel);
imagePanel.addMouseListener(mover);
imagePanel.addMouseMotionListener(mover);
ipanel = imagePanel.getPanel();
ipanel.setBorder(new LineBorder(Color.blue,1));
ipanel.setBorder(BorderFactory.createTitledBorder("Scanned Image"));
ipanel.setBounds(0, 30,600, 600);
ipanel.repaint();
ipanel.revalidate();
ipanel.updateUI();
jContentPane.add(ipanel);
jContentPane.getRootPane().revalidate();
jContentPane.updateUI();
//jContentPane.repaint();
// cimg=imagePanel.getCimg();
// ImagePanel cpanel = (ImagePanel) imagePanel.getUIPanel();
/*
cpanel.setBounds(700, 30,600, 800);
jContentPane.add(imagePanel.getUIPanel());
*/
cpanel = imagePanel.getUIPanel();
cpanel.setBounds(700, 30,300, 150);
cpanel.repaint();
cpanel.setBorder(new LineBorder(Color.blue,1));
cpanel.setBorder(BorderFactory.createTitledBorder("Cropping Image"));
jContentPane.add(cpanel);
jContentPane.repaint();
jContentPane.revalidate();
metadata.setImage(null);
try {
new uk.co.mmscomputing.concurrent.Semaphore(0, true).tryAcquire(2000, null);
} catch (InterruptedException e) {
IJ.error(e.getMessage());
}
}
else if (type.equals(ScannerIOMetadata.NEGOTIATE)) {
ScannerDevice device = metadata.getDevice();
try {
device.setResolution(100);
} catch (ScannerIOException e) {
IJ.error(e.getMessage());
}
try{
device.setShowUserInterface(false);
// device.setShowProgressBar(true);
// device.setRegionOfInterest(0,0,210.0,300.0);
device.setResolution(100); }catch(Exception e){
e.printStackTrace(); }
}
else if (type.equals(ScannerIOMetadata.STATECHANGE)) {
System.out.println("Scanner State "+metadata.getStateStr());
System.out.println("Scanner State "+metadata.getState());
//switch (metadata.ACQUIRED){};
ts = ((TwainIOMetadata)metadata).getSource();
//ts.setCancel(false);
//ts.getState()
//TwainConstants.STATE_TRANSFERREADY
((TwainIOMetadata)metadata).setState(6);
if ((metadata.getLastState() == 3) && (metadata.getState() == 4)){}
// IJ.error(metadata.getStateStr());
}
else if (type.equals(ScannerIOMetadata.EXCEPTION)) {
IJ.error(metadata.getException().toString());
}
}
public void stop(){ // execute before System.exit
if(scanner!=null){ // make sure user waits for scanner to finish!
scanner.waitToExit();
ts.setCancel(true);
try {
scanner.setCancel(true);
} catch (ScannerIOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm not an expert, but when ScannerIOMetadata.STATECHANGE shouldn't you check if the scanning is complete?
And if it is you should initialize the scanner again.
Something like that:
if (metadata.isFinished())
{
twainScanner = (TwainScanner) Scanner.getDevice();
}
I want to calculate the max, min and average time for which the beep was high from mic input.
Following is the code to capture an playbak it from mic. But I want to sense the beep sound coming and calculate time of each beep.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.sound.sampled.*;
public class AudioCapture01 extends JFrame{
boolean stopCapture = false;
ByteArrayOutputStream
byteArrayOutputStream;
AudioFormat audioFormat;
TargetDataLine targetDataLine;
AudioInputStream audioInputStream;
SourceDataLine sourceDataLine;
public static void main(String args[]){
new AudioCapture01();
}//end main
public AudioCapture01(){ //constructor
final JButton captureBtn = new JButton("Capture");
final JButton stopBtn = new JButton("Stop");
final JButton playBtn = new JButton("Playback");
captureBtn.setEnabled(true);
stopBtn.setEnabled(false);
playBtn.setEnabled(false);
setResizable(false);
setLocationRelativeTo(null);
//Register anonymous listeners
captureBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
captureBtn.setEnabled(false);
stopBtn.setEnabled(true);
playBtn.setEnabled(false);
//Capture input data from the microphone until the Stop button is clicked.
captureAudio();
}//end actionPerformed
}//end ActionListener
);//end addActionListener()
getContentPane().add(captureBtn);
stopBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
captureBtn.setEnabled(true);
stopBtn.setEnabled(false);
playBtn.setEnabled(true);
//Terminate the capturing of input data from the microphone.
stopCapture = true;
}//end actionPerformed
}//end ActionListener
);//end addActionListener()
getContentPane().add(stopBtn);
playBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Play back all of the data that was saved during capture.
playAudio();
}//end actionPerformed
}//end ActionListener
);//end addActionListener()
getContentPane().add(playBtn);
getContentPane().setLayout(new FlowLayout());
setTitle("Capture/Playback Demo");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300,70);
setVisible(true);
}//end constructor
//This method captures audio input from a microphone and saves it in a ByteArrayOutputStream object.
private void captureAudio(){
try{
//Get everything set up for capture
audioFormat = getAudioFormat();
DataLine.Info dataLineInfo =new DataLine.Info(TargetDataLine.class,audioFormat);
targetDataLine = (TargetDataLine)AudioSystem.getLine(dataLineInfo);
targetDataLine.open(audioFormat);
targetDataLine.start();
//Create a thread to capture the microphone data and start it
// running. It will run until the Stop button is clicked.
Thread captureThread =new Thread(new CaptureThread());
captureThread.start();
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}//end catch
}//end captureAudio method
//This method plays back the audio
// data that has been saved in the
// ByteArrayOutputStream
private void playAudio() {
try{
//Get everything set up for
// playback.
//Get the previously-saved data
// into a byte array object.
byte audioData[] =byteArrayOutputStream.toByteArray();
//Get an input stream on the
// byte array containing the data
InputStream byteArrayInputStream= new ByteArrayInputStream(audioData);
AudioFormat audioFormat =getAudioFormat();
audioInputStream =new AudioInputStream(byteArrayInputStream,audioFormat,audioData.length/audioFormat.getFrameSize());
DataLine.Info dataLineInfo =new DataLine.Info(SourceDataLine.class,audioFormat);
sourceDataLine = (SourceDataLine)AudioSystem.getLine(dataLineInfo);
sourceDataLine.open(audioFormat);
sourceDataLine.start();
//Create a thread to play back
// the data and start it
// running. It will run until
// all the data has been played
// back.
Thread playThread =new Thread(new PlayThread());
playThread.start();
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}//end catch
}//end playAudio
//This method creates and returns an
// AudioFormat object for a given set
// of format parameters. If these
// parameters don't work well for
// you, try some of the other
// allowable parameter values, which
// are shown in comments following
// the declarations.
private AudioFormat getAudioFormat(){
float sampleRate = 8000.0F; //8000,11025,16000,22050,44100
int sampleSizeInBits = 16; //8,16
int channels = 1; //1,2
boolean signed = true; //true,false
boolean bigEndian = false; //true,false
return new AudioFormat(sampleRate,sampleSizeInBits,channels,signed,bigEndian);
}//end getAudioFormat
//===================================//
Inner class to capture data from microphone
class CaptureThread extends Thread {
//An arbitrary-size temporary holding buffer
byte tempBuffer[] = new byte[10000];
public void run(){
byteArrayOutputStream =new ByteArrayOutputStream();
stopCapture = false;
try{//Loop until stopCapture is set
// by another thread that
// services the Stop button.
while(!stopCapture){
//Read data from the internal
// buffer of the data line.
int cnt = targetDataLine.read(tempBuffer,0,tempBuffer.length);
if(cnt > 0){
//Save data in output stream object.
byteArrayOutputStream.write(tempBuffer, 0, cnt);
}//end if
}//end while
byteArrayOutputStream.close();
}catch (Exception e) {
System.out.println(e);
System.exit(0);
}//end catch
}//end run
}//end inner class CaptureThread
//===================================//
//Inner class to play back the data that was saved.
class PlayThread extends Thread{
byte tempBuffer[] = new byte[10000];
public void run(){
try{
int cnt;
//Keep looping until the input read method returns -1 for empty stream.
while((cnt = audioInputStream.
read(tempBuffer, 0,
tempBuffer.length)) != -1){
if(cnt > 0){
//Write data to the internal buffer of the data line
// where it will be delivered to the speaker.
sourceDataLine.write(tempBuffer, 0, cnt);
}//end if
}//end while
//Block and wait for internal buffer of the data line to empty.
sourceDataLine.drain();
sourceDataLine.close();
}catch (Exception e) {
System.out.println(e);
System.exit(0);
}//end catch
}//end run
}//end inner class PlayThread
}//end outer class AudioCapture01.java
I am able to capture and playback the audio but I can't sense the audio. Any help will be appreciated.