⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 swingrec.java

📁 Sound recorder application using swing...
💻 JAVA
字号:
/*
	This file is part of SwingRec version 1.0
	Coded / Copyright 2005 by Bert Szoghy
	webmaster@quadmore.com
	This program is free software; you can redistribute it and/or modify it under the terms
	of the GNU General Public License version 2 as published by the Free Software Foundation;
	This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
	the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
	See the GNU General Public License for more details. You should have received a copy of
	the GNU General Public License along with this program; if not, write to the
	Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

	Tip of the hat to the command line SimpleAudioRecorder.java by Matthias Pfisterer
	at jsresources.org
*/
import javax.swing.Timer;
import java.io.IOException;
import java.io.File;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.AudioFileFormat;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.net.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import java.io.*;
import java.util.*;
import java.net.*;

public class SwingRec extends JPanel
{
	private TargetDataLine m_line;
	private AudioFileFormat.Type m_targetType;
	private AudioInputStream m_audioInputStream;
	private File m_outputFile;
	private Timer timer;
	private Timer timertwo;
	private JTextField txtEmailHere;
	private JTextField txtStatus;
	private JCheckBox chkUpload;
	private JTextField txtURLHere;

	public SwingRec()
	{
		final JButton m_Start;
		final JButton m_Stop;
		JPanel p = new JPanel();
		p.add(new JLabel("Click button to begin recording your voice (microphone must be plugged in!)"));
		add(p);

		p = new JPanel();
		m_Start = new JButton("Click to start recording");
		p.add(m_Start);
		add(p);

		m_Start.setBackground(Color.black);
		m_Start.setForeground(Color.white);

		p = new JPanel();
		m_Stop = new JButton("Click to stop recording");
		p.add(m_Stop);
		add(p);
		m_Stop.setVisible(false);

		p = new JPanel();
		JCheckBox chkUpload = new JCheckBox("Check to prevent upload");
		p.add(chkUpload);
		add(p);

		chkUpload.addItemListener(new java.awt.event.ItemListener()
		{
			public void itemStateChanged(ItemEvent e)
			{
				if (e.getStateChange() == ItemEvent.DESELECTED)
				{
					GlobalStorage.setUploadFile(true);
					System.out.println("File will be uploaded\n");
				}
				else
				{
					GlobalStorage.setUploadFile(false);
					System.out.println("File will NOT be uploaded\n");
				}
			}
		 });

		ActionListener btnStartClicked = new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				//Switch buttons:
				GlobalStorage.setTickingClock(10);
				txtStatus.setText("Time Left: 10 seconds...");
				m_Stop.setVisible(true);
				m_Start.setVisible(false);
				txtStatus.setVisible(true);
				GlobalStorage.setStopIsNext(true);
				repaint();

				//New thread to limit the recording to ten seconds
				final SwingWorker clockwatcherworker = new SwingWorker()
				{
					public Object construct()
					{
						repaint();

						timertwo = new Timer(1000, new ActionListener()
						{
							public void actionPerformed(ActionEvent evt)
							{
								if(GlobalStorage.isStopIsNext())
								{
									if(GlobalStorage.getTickingClock() == 1)
									{
										GlobalStorage.setStopIsNext(false);
										txtStatus.setVisible(false);
										m_Stop.setVisible(false);
										m_Start.setVisible(true);
										repaint();
										timertwo.stop();
									}
									else if(GlobalStorage.getTickingClock() == 2)
									{
										GlobalStorage.setTickingClock(GlobalStorage.getTickingClock() - 1);
										txtStatus.setText("Time left: 1 second...");
										repaint();
									}
									else
									{
										GlobalStorage.setTickingClock(GlobalStorage.getTickingClock() - 1);
										txtStatus.setText("Time left: " + String.valueOf(GlobalStorage.getTickingClock()) + " seconds...");
										repaint();
									}
								}
								else
								{
									txtStatus.setVisible(false);
									timertwo.stop();
								}
							}
						});
						timertwo.start();

						return "dummy value";
					}
				};
				clockwatcherworker.start();

				//New thread
				final SwingWorker worker = new SwingWorker()
				{
					public Object construct()
					{
						Date now = new Date();
      					long nowLong = now.getTime();
						String	strFilename;

						// Next line compiles in JDK 5 Update 1 but not JDK 1.4.2_07
						//strFilename = nowLong.toString();

						strFilename = String.valueOf(nowLong);
						GlobalStorage.setFilename(strFilename + ".wav");
						System.out.println("Filename will be..." + GlobalStorage.getFilename());

						File outputFile = new File(strFilename + ".wav");

						// Using PCM 44.1 kHz, 16 bit signed stereo.
						AudioFormat	audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,44100.0F, 16, 2, 4, 44100.0F, false);

						DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat);
						TargetDataLine	targetDataLine = null;

						try
						{
							targetDataLine = (TargetDataLine) AudioSystem.getLine(info);
							targetDataLine.open(audioFormat);
						}
						catch (LineUnavailableException e)
						{
							System.out.println("unable to get a recording line");
							e.printStackTrace();
							System.exit(1);
						}

						AudioFileFormat.Type targetType = AudioFileFormat.Type.WAVE;

						final Recorder recorder = new Recorder(targetDataLine,targetType,outputFile);

						int number = 0;
						System.out.println("Recording...");
						recorder.start();

						timer = new Timer(1000, new ActionListener()
						{
							int d = 0;

							public void actionPerformed(ActionEvent evt)
							{
								if(!(GlobalStorage.isStopIsNext()))
								{
									// Here, the recording is stopped.
									recorder.stopRecording();
		 							timer.stop();
									GlobalStorage.setTickingClock(10);
									System.out.println("Recording stopped.");
									if(GlobalStorage.isUploadFile())
									{
										JavaToPHP jtp = new JavaToPHP();
										jtp.start();
									}
								}
							}
						});
						timer.start();

						return "dummy value";
					}
				};
				worker.start(); //required for SwingWorker 3 Class
			}
		};

		m_Start.addActionListener(btnStartClicked);

		ActionListener btnStopClicked = new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				GlobalStorage.setStopIsNext(false);
				m_Stop.setVisible(false);
				m_Start.setVisible(true);
				txtStatus.setVisible(false);
				repaint();
			}
		};

		m_Stop.addActionListener(btnStopClicked);

		p = new JPanel();
		p.add(new JLabel("Email address where the server response should be sent to:"));
		add(p);

		p = new JPanel();
		txtEmailHere = new JTextField(30);

		//workaround for bug that makes text field not get focus
			txtEmailHere.addMouseListener(new MouseAdapter() {
			    public void mouseDown(MouseEvent e) {
				txtEmailHere.requestFocus();
			    }
		});

		txtEmailHere.getDocument().addDocumentListener(new DocumentListener()
		{
		        public void changedUpdate(DocumentEvent e)
		        {
		            GlobalStorage.setEmail(txtEmailHere.getText());
		        }

		        public void insertUpdate(DocumentEvent e)
		        {
		           GlobalStorage.setEmail(txtEmailHere.getText());
		        }

		        public void removeUpdate(DocumentEvent e)
		        {
		            GlobalStorage.setEmail(txtEmailHere.getText());
		        }
		    }
		);

		p.add(txtEmailHere );
		add(p);
		txtEmailHere.setEditable(true);

		p = new JPanel();
		p.add(new JLabel("Enter alternate URL below if you do not want: " + GlobalStorage.getURL()));
		add(p);


		p = new JPanel();
		txtURLHere = new JTextField(45);

		//workaround for bug that makes text field not get focus
			txtURLHere.addMouseListener(new MouseAdapter() {
			    public void mouseDown(MouseEvent e) {
				txtURLHere.requestFocus();
			    }
		});

		txtURLHere.getDocument().addDocumentListener(new DocumentListener()
		{
		        public void changedUpdate(DocumentEvent e)
		        {
		            GlobalStorage.setURL(txtURLHere.getText());
		        }

		        public void insertUpdate(DocumentEvent e)
		        {
		           GlobalStorage.setURL(txtURLHere.getText());
		        }

		        public void removeUpdate(DocumentEvent e)
		        {
		            GlobalStorage.setURL(txtURLHere.getText());
		        }
		    }
		);

		p.add(txtURLHere );
		add(p);
		txtURLHere.setEditable(true);

		txtStatus = new JTextField("Time Left: 10 seconds...");
		txtStatus.setEditable(false);
		txtStatus.setBorder(BorderFactory.createBevelBorder(1));
		txtStatus.setHorizontalAlignment(JTextField.CENTER);
		txtStatus.setForeground(Color.blue);
		p = new JPanel();
		p.add(txtStatus);
		add(p);
		txtStatus.setVisible(false);
	}

	public static void main(String s[])
	{
		 JFrame frame = new JFrame("Record a voice command and upload it to a web server");
		 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		 frame.setContentPane(new SwingRec());
		 frame.setSize(550,270);
		 frame.setLocation(100,100);
		 frame.setVisible(true);
    }

	public void start()
	{
		m_line.start();
	}

	public void stopRecording()
	{
		m_line.stop();
		m_line.close();
	}

	public void run()
	{
		try
		{
			AudioSystem.write(m_audioInputStream,m_targetType,m_outputFile);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -