
Originariamente inviata da
andbaz
Allora ho provato a fare come mi hai detto ma non riesco a far passare la variabile type in keyPressed...purtroppo con java ho ancora poca confidenza
In ogni caso ho provato a fare anche così ma non funziona, le ho provate tutte e l'ultima è questa ma non riesco a passare audioClip in keyPressed
codice:
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.sound.sampled.*;
public class x extends JFrame
implements KeyListener,
ActionListener,
LineListener
{
JTextField typingArea;
static String audioFilePath;
boolean playCompleted;
public static Clip audioClip;
public static void main(String[] args) {
x frame = new x("x");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addComponentsToPane();
frame.pack();
frame.setVisible(true);
try {
String audioFilePath = "/C:/Users/user/Desktop/ECLIPSE/1/bin/65.wav";
File audioFile = new File(audioFilePath);
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip audioClip = (Clip) AudioSystem.getLine(info);
audioClip.open(audioStream);
} catch (UnsupportedAudioFileException ex) {
ex.printStackTrace();
} catch (LineUnavailableException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void keyPressed(KeyEvent e) {
audioClip.stop();
((Clip) audioClip).setFramePosition(0);
audioClip.start();
audioClip.addLineListener((LineListener) this);
}
private void addComponentsToPane() {
typingArea = new JTextField();
typingArea.addKeyListener(this);
getContentPane().add(typingArea, BorderLayout.PAGE_START);
}
public x(String name) {
super(name);
}
@Override
public void update(LineEvent event) {
LineEvent.Type type = event.getType();
if (type == LineEvent.Type.START) {
playCompleted = false;
System.out.println("START");
} else if (type == LineEvent.Type.STOP) {
playCompleted = true;
System.out.println("STOP");
}
}
}