1 Replies - 19546 Views - Last Post: 04 March 2009 - 11:05 PM Rate Topic: -----

#1 kummu4help  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 4
  • View blog
  • Posts: 245
  • Joined: 05-August 08

how to save ByteArrayOutputStream as a file

Post icon  Posted 04 March 2009 - 09:33 PM

hi
i have a thread in which i am capturing the audio into a bytearrayoutputstream. i want to save this bytearray as a file. how can i do this
class CaptureThread extends Thread{
  //An arbitrary-size temporary holding buffer
  byte tempBuffer[] = new byte[10000];
		@Override
  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



actually i got this program from a site. the main purpose is to capture an audio from microphone and play it again
i am trying to use this concept with an applet.
i want to change the captured audio to a file. so that i want to write another applet and using that i want to play the file
the complete source is here.

package javaapplication1;


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.sound.sampled.*;

public class AudioCapture02 extends JFrame{

  boolean stopCapture = false;
  ByteArrayOutputStream byteArrayOutputStream;
  AudioFormat audioFormat;
  TargetDataLine targetDataLine;
  AudioInputStream audioInputStream;
  SourceDataLine sourceDataLine;

  public static void main(String args[]){
	new AudioCapture02();
  }//end main

  public AudioCapture02(){//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);

	//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(250,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 and display a list of
	  // available mixers.
	  Mixer.Info[] mixerInfo =
					  AudioSystem.getMixerInfo();
	  System.out.println("Available mixers:");
	  for(int cnt = 0; cnt < mixerInfo.length;
										  cnt++){
		  System.out.println(mixerInfo[cnt].
										getName());
	  }//end for loop

	  //Get everything set up for capture
	  audioFormat = getAudioFormat();

	  DataLine.Info dataLineInfo =
							new DataLine.Info(
							TargetDataLine.class,
							audioFormat);

	  //Select one of the available
	  // mixers.
	  Mixer mixer = AudioSystem.
						  getMixer(mixerInfo[3]);

	  //Get a TargetDataLine on the selected
	  // mixer.
	  targetDataLine = (TargetDataLine)
					 mixer.getLine(dataLineInfo);
	  //Prepare the line for use.
	  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 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 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 declartions.
  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];
		@Override
  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];

		@Override
  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 AudioCapture02.java





thanks for any help

Is This A Good Question/Topic? 0
  • +

Replies To: how to save ByteArrayOutputStream as a file

#2 kummu4help  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 4
  • View blog
  • Posts: 245
  • Joined: 05-August 08

Re: how to save ByteArrayOutputStream as a file

Posted 04 March 2009 - 11:05 PM

now i changed my code like this to avoid the bytestreams.

this is working fine but the problem is it is not capturing the audio.
a file is being created with extension ".wav" but when i try to play it, no audio is audible. i mean it is not capturing any thing. i can here only silence.

any help pls...

 
import javax.swing.*;			   
//Need to import all these files for it to work
import java.awt.event.*;
import java.awt.*;
import javax.sound.sampled.*;
import java.io.*;
class demo extends Frame  //Main class
{
  JButton start;
  JButton stop;
  boolean stopCapture = false;
  ByteArrayOutputStream byteArrayOutputStream;
  AudioFormat audioFormat;
  TargetDataLine targetDataLine;
  AudioInputStream audioInputStream;
  SourceDataLine sourceDataLine;
	 //sets variable button to a JButton
	 public int Count = 0;	 //makes public integer Count

	
	 demo()		  //Function for initialization
	 {
		super("MyAudioDemo");
		  start = new JButton("start");
		  stop = new JButton("stop");//Creates a new JButton that says "Click"
		 
		 setLayout(new FlowLayout()); // Sets the button layout
		  start.addActionListener(new StartListener());
		  stop.addActionListener(new StopListener());
//Adds a listener, so action can be performed if clicked
		  start.setBackground(Color.yellow);
		  stop.setBackground(Color.yellow);//Makes color yellow
		 add(start);
		 add(stop);//Makes button visible in the window
		 setSize(600,200);
	 }

	 private class StartListener implements ActionListener  //The listener class
	 {
		  public void actionPerformed(ActionEvent push)  
//If button is clicked...will run this
		  {
			  
			   Count++;   //Adds 1 to Count			   
			   start.setText(Integer.toString(Count));
			   //Changes text of button to the value of Count
			   captureAudio();
			  
		  }
	 }
	 private class StopListener implements ActionListener  
//The listener class
	 {
		  public void actionPerformed(ActionEvent push)  
//If button is clicked...will run this
		  {						
			   stopCapture = true;
			   System.exit(0);
		  }
	 }
private void captureAudio(){
	try{
	  //Get things set up for capture
	  audioFormat = getAudioFormat();
	  DataLine.Info dataLineInfo =
						  new DataLine.Info(
							TargetDataLine.class,
							audioFormat);
	  targetDataLine = (TargetDataLine)
			   AudioSystem.getLine(dataLineInfo);

	  //Create a thread to capture the microphone
	  // data into an audio file and start the
	  // thread running.  It will run until the
	  // Stop button is clicked.  This method
	  // will return after starting the thread.
	  new CaptureThread().start();
	}catch (Exception e) {
	  e.printStackTrace();
	  System.exit(0);
	}//end catch
  }//end captur
 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

 class CaptureThread extends Thread{
	 @Override
	 public void run(){		 

   AudioFileFormat.Type fileType = null;
	File audioFile = null;
	fileType = AudioFileFormat.Type.WAVE;
	audioFile = new File("E:/junk.wav");

	try{
	  targetDataLine.open(audioFormat);
	  targetDataLine.start();
	  AudioSystem.write(
			new AudioInputStream(targetDataLine),
			fileType,
			audioFile);
	}catch (Exception e){
	  e.printStackTrace();
	}//end catch
  }//end run
}
}
public class Main {

	/**
	 * @param args the command line arguments
	 */
	public static void main(String[] args) {
		// TODO code application logic here
		demo Demo = new demo();
		Demo.setVisible(true);
	}

}





the below thread is creating captured audio file
 class CaptureThread extends Thread{
	 @Override
	 public void run(){		 

   AudioFileFormat.Type fileType = null;
	File audioFile = null;
	fileType = AudioFileFormat.Type.WAVE;
   [b] audioFile = new File("E:/junk.wav");[/b]

	try{
	  targetDataLine.open(audioFormat);
	  targetDataLine.start();
	  AudioSystem.write(
			new AudioInputStream(targetDataLine),
			fileType,
			audioFile);
	}catch (Exception e){
	  e.printStackTrace();
	}//end catch
  }//end run
}



thanks for any help
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1