Results 1 to 2 of 2
  1. #1
    Saran185 is offline Member
    Join Date
    Jan 2011
    Posts
    36
    Rep Power
    0

    Question pause threads on button click

    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..
    Java 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(" \n 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<r.length;j++)                      
    		              { textArea1.append(r[j]);       // display text in text area when audio plays                         
    		              textArea1.append(" ");
    		              textArea1.setForeground(Color.red);
    					  textArea1.setLineWrap(true);
    					  int t=dur/nbWords;                 // calc time as audio file duration/ total words in text file    
    		     		  Thread.currentThread().sleep(t); 
                 					  //  make the thread2 to sleep fot 't' time
    					  dur=dur-t;                          // decrease dur 
    					  nbWords--;                         // decrement total word count
    		              
    		              }          
    	                }
    					catch (InterruptedException x) 
    					            {
    	                      x.printStackTrace();
                                      }
    		           }             
    		         };
    		           Thread tr2 = new Thread(r2);                             
    		          tr2.start();
    				  
                    
    	 
    	  }
    	  
    Runnable r1 = new Runnable()                              // thread 1 for playing audio file
    		{
    		public void run() 
    		{
                    try 
    				{
    			     
                   			// calling play function
    				}
                    catch (Exception e) { System.out.println(e); }
    				
    				
    				
    				
            }
    	    };
    		Thread tr1 = new Thread(r1);
    		
    		
    		
    
    	  ActionListener pauseListener = 
            new ActionListener() {
          public void actionPerformed(ActionEvent e) {
    		System.out.println("paused");
    		//tr1.sleep();
    		//s1();
    		 
    				   tr1.suspend();
    				  
    				  
    		
          }
        };
    	
    	  ActionListener play1Listener = 
            new ActionListener() {
          public void actionPerformed(ActionEvent e) {
    		System.out.println("played");
    		//tr1.notify();
    		//res();
    		 
    				   tr1.resume();
    				  
    				 
          }
        };
    	
    				  
     ActionListener actionListener = new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
    JFrame frm2 = new JFrame();                        // actions performed when record btn is clicked
    	   frm2.setSize(1000, 735);
           frm2.setVisible(true);                        // a new frame is created-frm2
    	   JMenuBar mb1 = new JMenuBar();                 // creating menu bar
           capture = new JButton("Capture");             // creating capture, stop and play btns
          stop = new JButton("Stop");
          play = new JButton("Play");
    	  mb1.add(capture);
    	  	  mb1.add(stop);
    	  mb1.add(play);                                  // adding buttons to menu bar
    	      capture.addActionListener(captureListener);  
    
    	      stop.addActionListener(stopListener); // adding action listener to buttons
    
    	  play.addActionListener(playListener);
    	 frm2.setJMenuBar(mb1);
    String command = actionEvent.getActionCommand();
    System.out.println("Selected: " + command);   
    }
    };
    ActionListener captureListener = 
            new ActionListener() {
          public void actionPerformed(ActionEvent e) {
    	  
            captureAudio();                                  // calling captureAudio() function when capture button is clicked
    		capture.setEnabled(false);
            stop.setEnabled(true);
            play.setEnabled(true);
          }
        };
    	ActionListener stopListener = 
            new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            capture.setEnabled(true);
            stop.setEnabled(false);                         // stop recording when 'stop' button is clicked
            play.setEnabled(true);
            running = false;
    		System.out.println("stopped");
          }
        };
    	ActionListener playListener = 
            new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            playAudio();                                      // calling 'playAudio' function when play button is clicked.
    		capture.setEnabled(true);                                  // plays the recorded audio
            stop.setEnabled(true);
            play.setEnabled(false);
          }
        };
           
               
          
      
    	  
    	 
    	  
        
    	private void captureAudio() {
        try { System.out.println("capturing");
          final AudioFormat format = getFormat();
          DataLine.Info info = new DataLine.Info(
            TargetDataLine.class, format);                        // sets the audio format for recording voice
          final TargetDataLine line = (TargetDataLine)
            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() {
              out = new ByteArrayOutputStream();
              running = true;
              try {
                while (running) {
                  int count = 
                    line.read(buffer, 0, buffer.length);
                  if (count > 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("\n 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;
    }
    }

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,874
    Rep Power
    8

    Default

    That is way too much code. Nobody is going to have time to wade through all of that. But I suggest you read through this tutorial: Lesson: Concurrency (The Java™ Tutorials > Essential Classes)
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

Similar Threads

  1. Button click GUI question
    By ZambonieDrivor in forum New To Java
    Replies: 2
    Last Post: 11-29-2010, 07:48 AM
  2. SaveAs button click
    By kasiram.p@gmail.com in forum AWT / Swing
    Replies: 2
    Last Post: 07-06-2010, 08:35 AM
  3. How can I display on Button click?
    By ntagrafix in forum New To Java
    Replies: 3
    Last Post: 11-04-2009, 12:05 AM
  4. deselecting a button after the click.
    By ramsrocker in forum New To Java
    Replies: 10
    Last Post: 02-15-2009, 06:52 AM
  5. How to perform some event to button click
    By eva in forum AWT / Swing
    Replies: 2
    Last Post: 01-16-2008, 12:27 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •