multi threading in java

hi..
I have my java code below. in dis i ve created a pause and play button. Already iam running two threads. One to play an audio file and other to display text. Now when i click the pause button both threads should stop
or suspend execution. and when i click the play button both threads should resume . I have used the suspend() and resume() functions.. But the threads are not pausing when i click the pause button. Can anyone fix where is the fault and guide me in dis..
[code]

import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.event.AncestorListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.text.DefaultEditorKit;
import javax.swing.*;
import javax.swing.JScrollPane;
import javax.swing.BoundedRangeModel;
import java.io.*;
import java.util.Scanner;
import java.lang.*;
import javax.sound.sampled.*;
import javax.sound.*;
import javax.sound.sampled.AudioSystem;
import java.util.*;
import javazoom.jl.decoder.*;
import javazoom.jl.player.Player;



public class hl1 implements MouseListener
{ // class "hl" opens
JFrame frm;
JTextArea textArea1;
JTextArea textArea2;
JScrollPane sp;
JScrollPane sp2;
Action selectWord;
private FileFilter fJavaFilter;
private File fFile;
String aufile;
String strLine;
String word;
JButton capture;
JButton stop;
JButton play;
int bufSize;
String [] s = new String[800];
String [] r=new String[500];
String [] r2=new String[500];
int nbWords;
int nTotalMS;
int dur;
boolean running;
String filename;
play p1;
ByteArrayOutputStream out;
Properties pro = new Properties();
public static void main(String[] args) throws InterruptedException // main
{
hl1 highlight = new hl1(); // creating instance for "hl"class
}

public hl1() // Constructor hl
{

frm = new JFrame(); // creating the frame elements
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setSize(1000, 735);
frm.setVisible(true);
JMenuItem fMenuOpen = null; // creating buttons in the menu bar
JMenu m = new JMenu("File"); // file menu item
m.add(fMenuOpen = makeMenuItem("Open"));
JMenuBar mb = new JMenuBar();
JButton b2 = new JButton("play"); // play button
b2.addActionListener(actionListenerplay); // action listener for play btn

mb.add(m); // add file menu item to menu bar
mb.add(b2); // add play btn to menu bar

JButton b1 = new JButton("record"); // record button
b1.addActionListener(actionListener); // action listener for record btn
mb.add(b1); // add record btn to menu bar
frm.setJMenuBar(mb);
textArea1 = new JTextArea(20,80); // create text area
textArea2 = new JTextArea(10,80);

sp = new JScrollPane(textArea1); // adding scrollpanes to text areas
sp2 = new JScrollPane(textArea2);
frm.setLayout(new FlowLayout());
frm.getContentPane().add(sp);
frm.getContentPane().add(sp2);
Icon image1 = new ImageIcon("pause.jpg");
JButton pause = new JButton();
pause.setIcon(image1);
pause.setAlignmentX(300);
frm.add(pause);

Icon image2 = new ImageIcon("play.jpg");
JButton play1 = new JButton();
play1.setAlignmentX(400);
play1.setIcon(image2);
frm.add(play1);
pause.addActionListener(pauseListener);

play1.addActionListener(play1Listener);
selectWord =getAction(DefaultEditorKit.selectWordAction); // for selecting word in text pane when the word is double clicked
textArea1.addMouseListener(this);


}

private Action getAction(String name) // textarea action
{
Action action = null;
Action[] actions = textArea1.getActions();
for (int i = 0; i < actions.length; i++) // if the word is double clicked on the text area the word will be highlighted
{
if (name.equals( actions[i].getValue(Action.NAME).toString() ) )
{
action = actions[i];
break;
}
}
return action;
}
ActionListener actionListenerplay =
new ActionListener() { // calling the function 'playfile' in action listener-
public void actionPerformed(ActionEvent e) { // when play btn is clicked 'playfile' is called

playFile();

}
};
class play // play class
{
private String filename;
public play(String filename) // constructor play
{ // assigning audio filename
this.filename = filename;

}
public void length() // calculating length of the audio file
{ try{File f1 = new File(filename);
FileInputStream fstr = new FileInputStream(f1);
Bitstream m_bitstream = new Bitstream(new FileInputStream(f1)); // reading data from audio file in bits
Header m_header = m_bitstream.readFrame();
int mediaLength = (int)f1.length(); // using function length()
int nTotalMS=0;
if (mediaLength != AudioSystem.NOT_SPECIFIED)
{
nTotalMS = Math.round(m_header.total_ms(mediaLength));
}
System.out.println("duration : "+nTotalMS);
dur=nTotalMS; // variable dur has the length of audio file in microsecs.
}catch (Exception e) {
System.out.println(e);
}

}

public void playw () // playing audio file
{
class MyLineListener implements LineListener {
public void update(LineEvent le) {
LineEvent.Type type = le.getType();
System.out.println(type);
}
};

try {
File f1 = new File(filename);
FileInputStream fin = new FileInputStream(f1); // reading file
AudioInputStream fis =
AudioSystem.getAudioInputStream(f1);

AudioInputStream ais = AudioSystem.getAudioInputStream(
AudioFormat.Encoding.PCM_SIGNED,fis);
AudioFormat af = ais.getFormat(); // get the format of audio file
System.out.println("AudioFormat: " + af.toString());
int frameRate = (int)af.getFrameRate(); // get frame rate of audio file
System.out.println("Frame Rate: " + frameRate);
float SampleRate = (int)af.getSampleRate();
System.out.println("Sample Rate: " + SampleRate); // get sample rate of audio file
int frameSize = af.getFrameSize();
System.out.println("Frame Size: " + frameSize); // get frame size of audio file
long frameLength = ais.getFrameLength();
System.out.println("Frame len: " + frameLength); // get frame length of audio file

SourceDataLine line = AudioSystem.getSourceDataLine(af);
line.addLineListener(new MyLineListener());

line.open(af);
int bufSize = line.getBufferSize(); // get buffer size of audio file
System.out.println("Buffer Size: " + bufSize);



line.start(); // start playing file

byte[] data = new byte[bufSize];
int bytesRead;

while ((bytesRead = ais.read(data,0,data.length)) != -1)
line.write(data,0,bytesRead); // plays until the buf size is over

line.drain();
line.stop();
line.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
public void playFile() // function playfile is called when play btn is clicked
{

String targetExtension=".mp3"; // setting target extension
int l=aufile.length();
if(l>=1)
{
String ext =aufile.substring(aufile.indexOf(".")); // converting txt to audio file
System.out.println(ext); // changing extension
if(ext.equalsIgnoreCase(".txt"))
{
File f = new File(aufile);

if(f.exists())
{
aufile=aufile.replace(ext,targetExtension);
System.out.println(" "+aufile);
filename = aufile;
textArea2.append("
Playing... " + filename);
try
{

play p1 = new play(filename); // creating instance for play class -p1
p1.length(); // calling length() - calc length of audio file
}
catch (Exception e)
{
System.out.println("Problem playing file " + filename);
System.out.println(e);
}

//play p1 = new play(filename);
Runnable r1 = new Runnable() // thread 1 for playing audio file
{
public void run()
{
try
{
play p1 = new play(filename);
p1.playw();
// calling play function
}
catch (Exception e) { System.out.println(e); }




}
};
Thread tr1 = new Thread(r1);

tr1.start();

}
}
}




Runnable r2 = new Runnable()
{ // thread 2 for displaying text in text area
public void run()
{
try
{
/*Scanner ins2 = new Scanner("c://program files/java.jdk1.6.0/bin/a1.txt");
int i=0;
String[] r2=new String[20]; // storing txt in 2 nd variable.
while(ins2.hasNext())
{
if(ins2.hasNext())
{
r2[i]=ins2.next();
i++;
}
}
ins2.close();
*/

for(int j=0;j 0) {
out.write(buffer, 0, count);
}
}
out.close();
} catch (IOException e) {
System.err.println("I/O problems: " + e);
System.exit(-1);
}
}
};
Thread captureThread = new Thread(runner); // run seperate thread for recording
captureThread.start();
} catch (LineUnavailableException e) {
System.err.println("Line unavailable: " + e);
System.exit(-2);
}
}
private void playAudio() {
try { System.out.println("playing");
byte audio[] = out.toByteArray();
InputStream input =
new ByteArrayInputStream(audio);
final AudioFormat format = getFormat();
final AudioInputStream ais =
new AudioInputStream(input, format,
audio.length / format.getFrameSize()); //play recorded audio
DataLine.Info info = new DataLine.Info(
SourceDataLine.class, format);
final SourceDataLine line = (SourceDataLine)
AudioSystem.getLine(info);
line.open(format);
line.start();

Runnable runner = new Runnable() {
int bufferSize = (int) format.getSampleRate()
* format.getFrameSize();
byte buffer[] = new byte[bufferSize];

public void run() {
try {
int count;
while ((count = ais.read(
buffer, 0, buffer.length)) != -1) {
if (count > 0) {
line.write(buffer, 0, count);
}
}
line.drain();
line.close();
} catch (IOException e) {
System.err.println("I/O problems: " + e);
System.exit(-3);
}
}
};
Thread playThread = new Thread(runner);
playThread.start();
} catch (LineUnavailableException e) {
System.err.println("Line unavailable: " + e);
System.exit(-4);
}
}

private AudioFormat getFormat() {
float sampleRate = 8000;
int sampleSizeInBits = 8;
int channels = 1;
boolean signed = true;
boolean bigEndian = true;

return new AudioFormat(sampleRate,
sampleSizeInBits, channels, signed, bigEndian);
}

public void mouseClicked(MouseEvent e)
{
if ( SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 1)
{ // when is the word in text area is double clicked the word get highlighted
selectWord.actionPerformed( null );
}
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
private JMenuItem makeMenuItem(String name) // action on clicking file menu
{
JMenuItem m = new JMenuItem(name);
m.addActionListener(new filemenu());
return m;
}
class filemenu implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
boolean status = false;
String command = e.getActionCommand(); // check for open menu item in file menu
if (command.equals("Open"))
{
status = openFile(); // call openfile() for open menu item
if (!status)
JOptionPane.showMessageDialog(null, "Error opening file!",
"File Open Error", JOptionPane.ERROR_MESSAGE);
}
}
}
boolean openFile() // filechooser for opening file
{
JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Open File");
fc.setFileSelectionMode(JFileChooser.FILES_ONLY); // Choose only files, not directories
fc.setCurrentDirectory(new File(".")); // Start in current directory
fc.setFileFilter(fJavaFilter); // Set filter for Java source files.
int result = fc.showOpenDialog(frm); // Now open chooser
if (result == JFileChooser.CANCEL_OPTION)
{
return true;
}
else if (result == JFileChooser.APPROVE_OPTION)
{
fFile = fc.getSelectedFile(); // get selected file and assign to variable fFile
aufile = fFile.getName(); // get the filename without extension

try
{
FileInputStream fstream = new FileInputStream(fFile);
DataInputStream in = new DataInputStream(fstream); // opening the selected file
BufferedReader br = new BufferedReader(
new InputStreamReader(in));
Scanner ins = new Scanner(fFile);
nbWords=0;
int i=0;
textArea2.setText(aufile);

while(ins.hasNext())
{
if(ins.hasNext())
{
// reading the contents of txt file
r[i]=ins.next();
// textArea1.append(r[i]);
// textArea1.append(" ");
i++;
}
nbWords++; // counting words in text file
}
textArea2.append("
word count: "+nbWords);

ins.close();

}
catch (Exception e)
{
System.err.println("Error: xyz" + e.getMessage());
}
System.out.println("end of open file");
}
else {
return false;
}
return true;
}
}

[/code]

Comments

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion