Перейти к содержимому

Фото
- - - - -

Java Applet


  • Вы не можете создать новую тему
  • Please log in to reply
2 ответов в этой теме

#1 Future Cut

Future Cut
  • Новобранец
  • 1 сообщений

Отправлено 12 марта 2008 - 11:13

Всем привет! У меня возникла такая проблема. Есть программа которая записывает звук с микрофона в файл. Мне нужно сделать из неё апплет что бы это могла работать в web'e. Аплет вроде бы готов, но в файл пишет только когда запускаю его в среде разработки(NetBeans IDE 6.0.1), а когда загружаю в html не работает. Браузер Opera 9.25. Вот код:

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

public class yoo extends Applet{
static final String Capt="capture", Stop="stop";
Font font;
  Button C = new Button(Capt);
  Button S = new Button (Stop);
public yoo(){

	C.setEnabled(true);
   S.setEnabled(false);

   //Register anonymous listeners
   C.addActionListener(
	 new ActionListener(){
	   public void actionPerformed(ActionEvent e){
		 C.setEnabled(false);
		 S.setEnabled(true);
		 //Capture input data from the
		 // microphone until the Stop button is
		 // clicked.
		 captureAudio();
	   }//end actionPerformed
	 }//end ActionListener
   );//end addActionListener()

   S.addActionListener(
	 new ActionListener(){
	   public void actionPerformed(
								 ActionEvent e){
		 C.setEnabled(true);
		S.setEnabled(false);
		 //Terminate the capturing of input data
		 // from the microphone.
		 targetDataLine.stop();
		 targetDataLine.close();
	   }//end actionPerformed
	 }//end ActionListener
   );//end addActionListener()

   //Put the buttons in the JFrame

   //Finish the GUI and make visible
}
int k=1;
TargetDataLine targetDataLine;
AudioFormat audioFormat;
public void init(){
	setLayout(new BorderLayout());
	//создаем новый объект типа Button ( кнопка ) 
		add("South",C);
		add("North",S);
	//задаём тип шрифта
	font=new Font("TimesRoman",Font.BOLD+Font.ITALIC,48);
}

public boolean handleEvent(Event evt){
	switch(evt.id){
	case Event.ACTION_EVENT : {
		if (( evt.arg==Capt)&&(k==2)){
			k=1;
			new CaptureThread().start();
		}
		else if((evt.arg==Stop)&&(k==1)){
			k=2;
			targetDataLine.stop();
		}
		else return false;
		 }
	default: return false;
	}
}
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);

   
	 new CaptureThread().start();
   }catch (Exception e) {
	 e.printStackTrace();
	 System.exit(0);
   }//end catch
 }//end captureAudio method

class CaptureThread extends Thread{
 public void run(){
   AudioFileFormat.Type fileType = null;
   File audioFile = null;

   //Set the file type and the file extension
   // based on the selected radio button.

	 fileType = AudioFileFormat.Type.WAVE;
	 audioFile = new File("junk.wav");

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

 }//end run
}//end inner class CaptureThread
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

 public static void main(String[] args) 
  {
   yoo   applet = new yoo ();
	  JFrame frame = new JFrame("TestApplet");
  // Для закрытия приложения:

  frame.getContentPane().add(applet);
  frame.setSize(400,450);
  applet.init();
  applet.start();
  frame.setVisible(true);
}

}

и html код:
<HTML>
<HEAD> 
<TITLE>Example</TITLE>
</HEAD>
<BODY> 
<APPLET CODE='yoo.class' WIDTH=150 HEIGHT=100>
</APPLET>
</BODY>
</HTML>

Буду рад любой помощи =)
  • 0

#2 shb

shb

    New life, much more options

  • Постоялец
  • 5 253 сообщений
  • Откуда:Таллинн

Отправлено 12 марта 2008 - 11:21

Была когда-то у меня загвоздка с апплетом и файлами. Каюсь, не разобрался до конца что и как надо делать.

Вроде апплет не может работать с файлами на машине пользователя. Защита от несанкционированной записи, считывания из веба.

Может надо какое подтверждение спрашивать у пользователя, не знаю :( Не докопал :)
  • 0
Мыслящий человек просто обязан время от времени поднимать себя за волосы © Тот самый Мюнгхаузен

Joga Bonito!

#3 Fors

Fors
  • Пользователь
  • 328 сообщений

Отправлено 15 марта 2008 - 10:51

http://java.sun.com/sfaq/

Я вижу только 1 солюшн - пускать через инет аудио поток к серверу, где он будет сливаться в файл, а после этого выдавать линк на скачку этого файла.
  • 0