Forme d'onde d'un signal audio java

Fermé
hammasaidi Messages postés 28 Date d'inscription lundi 1 février 2010 Statut Membre Dernière intervention 21 avril 2010 - 28 févr. 2010 à 23:20
Bonjour,
suis débutant en java et svp quelqu'un qui peut m'aider
de compiler mon code java
je veux représenter la waveform dans le canevas
/**
* @(#)Framework.java
*
*
* @author
* @version 1.00 2010/1/3
*/
import java.io.File;
import javax.swing.JLabel;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.swing.event.MouseInputAdapter;
import javax.swing.event.*;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;
import javax.swing.JSlider;
import javax.swing.JOptionPane;
import java.io.*;
import javax.sound.sampled.*;
import java.awt.*;
import java.awt.event.*;
import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Vector;
import java.awt.*;
import java.awt.geom.AffineTransform;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;


/* Framework.java requires no other files. */
public class Framework extends WindowAdapter {
public int numWindows = 0;
private Point lastLocation = null;
private int maxX = 500;
private int maxY = 500;

public Framework() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
maxX = screenSize.width - 50;
maxY = screenSize.height - 50;
makeNewWindow();

}

public void makeNewWindow() {


JFrame frame = new MyFrame(this);
numWindows++;
System.out.println("Number of windows: " + numWindows);






if (lastLocation != null) {
//Move the window over and down 40 pixels.
lastLocation.translate(40, 40);
if ((lastLocation.x > maxX) || (lastLocation.y > maxY)) {
lastLocation.setLocation(0, 0);
}
frame.setLocation(lastLocation);
} else {
lastLocation = frame.getLocation();
}

System.out.println("Frame location: " + lastLocation);
frame.setVisible(true);

}

//This method must be evoked from the event-dispatching thread.
public void quit(JFrame frame) {
if (quitConfirmed(frame)) {
System.out.println("Quitting.");
System.exit(0);
}
System.out.println("Quit operation not confirmed; staying alive.");
}


public void windowClosed(WindowEvent e) {
numWindows--;
System.out.println("Number of windows = " + numWindows);
if (numWindows <= 0) {
System.out.println("All windows gone. Bye bye!");
System.exit(0);
}
}
private boolean quitConfirmed(JFrame frame) {
String s1 = "Quit";
String s2 = "Cancel";
Object[] options = {s1, s2};
int n = JOptionPane.showOptionDialog(frame,
"Vous voulez vraiment Quiter?",
"Quit Confirmation",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
s1);
if (n == JOptionPane.YES_OPTION) {
return true;
} else {
return false;
}
}





/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
Framework framework = new Framework();

}

public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

class MyFrame extends JFrame implements ActionListener {
protected Dimension defaultSize = new Dimension(900, 600);
protected Framework framework = null;
private JLabel l1;
private JButton b_play;
private JButton b_stop;
private JButton b_ouvrir;
private JCheckBox ch5;
private File fichier = null;
private AudioFormat format;
private byte[] samples;
private JFileChooser jfc = new JFileChooser();

JFileChooser fc;

public void sound()
{
try
{
AudioInputStream stream = AudioSystem.getAudioInputStream(this.fichier);
this.format = stream.getFormat();
this.getSamples(stream);
}
catch (Exception e){}
}
public void getSamples(AudioInputStream stream)
{
int length = (int)(stream.getFrameLength() * format.getFrameSize());
this.samples = new byte[length];
DataInputStream in = new DataInputStream(stream);
try
{
in.readFully(this.samples);
}
catch (IOException e){}
}

public byte[] getSamples()
{
return this.samples;
}
public void play(InputStream source)
{
// 100 ms buffer for real time change to the sound stream
int bufferSize = this.format.getFrameSize() * Math.round(this.format.getSampleRate() / 10);
byte[] buffer = new byte[bufferSize];
SourceDataLine line;
try
{
DataLine.Info info = new DataLine.Info(SourceDataLine.class, this.format);
line = (SourceDataLine)AudioSystem.getLine(info);
line.open(this.format, bufferSize);
line.start();
int numBytesRead = 0;
while (numBytesRead != -1 && ! Thread.currentThread().interrupted())
{
numBytesRead = source.read(buffer, 0, buffer.length);
if (numBytesRead != -1)
line.write(buffer, 0, numBytesRead);
}
line.drain();
line.close();
}
catch (Exception e){}
}
public void ouvrir()
{
this.jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
this.jfc.addChoosableFileFilter(new FiltreExtension(".wav", "Fichier wav"));
this.jfc.addChoosableFileFilter(new FiltreExtension(".wav", "Fichier wav"));
int returnVal = this.jfc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
this.fichier = this.jfc.getSelectedFile();
}
}
private class Lecture
extends Thread
{
public void run()
{
play(new ByteArrayInputStream(getSamples()));
}
}

protected double biggestSample;
private AudioInputStream audioInputStream;
private int[][] samplesContainer;
public void AudioInfo(AudioInputStream stream) {
this.audioInputStream = stream;
sound();
}
public double getFileLengthSeconds(){
return audioInputStream.getFrameLength() / audioInputStream.getFormat().getFrameRate();
}
public int getNumberOfChannels(){
int numBytesPerSample = audioInputStream.getFormat().getSampleSizeInBits() / 8;
return audioInputStream.getFormat().getFrameSize() / numBytesPerSample;
}
public double getXScaleFactor(int panelWidth){
return (panelWidth / ((double) samplesContainer[0].length));
}

public double getYScaleFactor(int panelHeight){
return (panelHeight / (biggestSample * 2 * 1.2));
}

public int[] getAudio(int channel){
return samplesContainer[channel];
}

protected int getIncrement(double xScale) {
try {
int increment = (int) (samplesContainer[0].length / (samplesContainer[0].length * xScale));
return increment;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
protected void drawWaveform(Graphics g, int[] samples) {
if (samples == null) {
return;
}

int oldX = 0;
int oldY = (int) (getHeight() / 2);
int xIndex = 0;

int increment = audioInputStream.getIncrement(audioInputStream.getXScaleFactor(getHeight()));
g.setColor(Color.red);

int t = 0;

for (t = 0; t < increment; t += increment) {
g.drawLine(oldX, oldY, xIndex, oldY);
xIndex++;
oldX = xIndex;
}

for (; t < samples.length; t += increment) {
double scaleFactor = audioInputStream.getYScaleFactor(getHeight());
double scaledSample = samples[t] * scaleFactor;
int y = (int) ((getHeight() / 2) - (scaledSample));
g.drawLine(oldX, oldY, xIndex, y);

xIndex++;
oldX = xIndex;
oldY = y;
}
}


public MyFrame(Framework controller) {
super("Traitement Numérique de signal ");
framework = controller;
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(framework);
setLocation(50,50);
setLayout(new BorderLayout());


JPanel p2 =new JPanel();


b_ouvrir = new JButton("Ouvrir");
p2.add(b_ouvrir);

this.b_ouvrir.addActionListener(this);
JLabel l1=new JLabel("***son***");
p2.add(l1);
b_play = new JButton("Play");
p2.add(b_play);
this.b_play.addActionListener(this);
b_stop = new JButton("Stop");
p2.add(b_stop);
this.b_stop.addActionListener(this);





JLabel l2=new JLabel("***visualiser signal***");
p2.add(l2);
JButton b5 = new JButton("play");
p2.add(b5);
JButton b7 = new JButton("stop");
p2.add(b7);
JButton b4 = new JButton("Spectr");
p2.add(b4);


JButton b6 = new JButton("EXIT");
p2.add(b6);
b6.addActionListener(new ActionListener() {//exit
public void actionPerformed(ActionEvent e) {
System.exit(0);



}});
add("North",p2);


JPanel p1=new JPanel();
p1.setLayout(new BorderLayout());
JPanel p3=new JPanel();


JCheckBox ch5= new JCheckBox("son");
p3.add(ch5);


JButton b10 = new JButton("fiche signal");
b10.setBounds(0,10,10,10);
p3.add(b10);


JButton b11 = new JButton("view");
b11.setBounds(0,110,10,10);

p3.add(b11);




p1.setBounds(0,100,100,100);
p1.add("North",p3);


add("West",p1);



Canvas c = new EssaiCanvas();
c.setBackground(Color.black);


add("Center",c);

/* JPanel p4=new JPanel();
JLabel lz= new JLabel("zoum en amplitude");
p4.add(lz);

JSlider s3=new JSlider();
s3.setBounds(0,10,10,10);

p4.add(s3);



add("South",p4);*/


JMenu menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_W);
JMenuItem item = null;
//close
item = new JMenuItem("Close");
item.setMnemonic(KeyEvent.VK_C);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Close window");
MyFrame.this.setVisible(false);
MyFrame.this.dispose();
}
});
menu.add(item);


//new
item = new JMenuItem("New");
item.setMnemonic(KeyEvent.VK_N);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("New window");
framework.makeNewWindow();
}
});
menu.add(item);
//open
item = new JMenuItem("Open");
item.setMnemonic(KeyEvent.VK_N);

menu.add(item);
//Enregistrer..
item = new JMenuItem("Save..");
item.setMnemonic(KeyEvent.VK_N);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc=new JFileChooser();
fc.showSaveDialog(MyFrame.this);
}
});
menu.add(item);
//Enregistrer sous
item = new JMenuItem("Save as...");
item.setMnemonic(KeyEvent.VK_N);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc=new JFileChooser();
fc.showSaveDialog(MyFrame.this);

}
});
menu.add(item);
//Import un siganl wav ou mp3
item = new JMenuItem("Importer un signal..");
item.setMnemonic(KeyEvent.VK_N);

menu.add(item);



//quit
item = new JMenuItem("Quit");
item.setMnemonic(KeyEvent.VK_Q);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Quit request");
framework.quit(MyFrame.this);
}
});
menu.add(item);

JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
setJMenuBar(menuBar);

setSize(defaultSize);
JMenu menu1 = new JMenu("Edit");
menu.setMnemonic(KeyEvent.VK_W);

// selection
item = new JMenuItem("Select....");
item.setMnemonic(KeyEvent.VK_N);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Edit");


}
});
menu1.add(item);
// Cut
item = new JMenuItem("Cut");
item.setMnemonic(KeyEvent.VK_N);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Copier");

}
});
menu1.add(item);
// Copier
item = new JMenuItem("Copie");
item.setMnemonic(KeyEvent.VK_N);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Copier");

}
});
menu1.add(item);

//coller

item = new JMenuItem("Paste");
item.setMnemonic(KeyEvent.VK_N);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Coller");

}
});
menu1.add(item);



menuBar.add(menu1);
setJMenuBar(menuBar);
JMenu menu2 = new JMenu("Aide");
menu.setMnemonic(KeyEvent.VK_W);

// Aide
item = new JMenuItem("Aide");
item.setMnemonic(KeyEvent.VK_N);

menu2.add(item);


menuBar.add(menu2);
setJMenuBar(menuBar);
}
public void actionPerformed(ActionEvent e){
Lecture t = new Lecture();

if(e.getSource().equals(this.b_ouvrir))
{
this.ouvrir();
}
if(e.getSource().equals(this.b_play))
{
if(this.fichier == null)
{
this.ouvrir();
this.sound();

t.start();
}
else
{

this.sound();
t.start();
}
}
if (e.getSource().equals(this.b_stop)) {
this.sound();
//t.stop();
t.interrupt();
t = null;
}

}


}
class EssaiCanvas extends Canvas {

private boolean init = true;



private ZoomAndPanListener zoomAndPanListener;

public EssaiCanvas() {
this.zoomAndPanListener = new ZoomAndPanListener(this);
this.addMouseListener(zoomAndPanListener);
// this.addMouseMotionListener(zoomAndPanListener);
this.addMouseWheelListener(zoomAndPanListener);
}

public void paint(Graphics g1) {
Graphics2D g = (Graphics2D) g1;
g.setBackground(Color.black);

if (init) {
// Initialize the viewport by moving the origin to the center of the window,
// and inverting the y-axis to point upwards.
init = false;

zoomAndPanListener.setCoordTransform(g.getTransform());
} else {
// Restore the viewport after it was updated by the ZoomAndPanListener
g.setTransform(zoomAndPanListener.getCoordTransform());
}


g.setColor(Color.lightGray);
int lineHeight = getHeight() / 2;
g.drawLine(0, lineHeight, (int)getWidth(), lineHeight);

}




}

}

class FiltreExtension
extends javax.swing.filechooser.FileFilter
{
private String extension;
private String description;
public FiltreExtension(String extension, String description)
{

if (extension.indexOf('.') == -1)
extension = "." + extension;

this.extension = extension;
this.description = description;
}
public boolean accept(File fichier)
{

if (fichier.getName().endsWith(extension))
return true;
// les répertoires aussi doivent être affichés dans la fenêtre du JFileChooser
else if (fichier.isDirectory())
return true;
return false;
}
public String getDescription()
{
// la description du fichier, que lâ€Ton associe à son extension, on a un
// affichage du type: "Fichier JPEG (*.jpg)"
return this.description + "(*" + extension + ")";
}
}




























class ZoomAndPanListener implements MouseListener, MouseMotionListener, MouseWheelListener {
public static final int DEFAULT_MIN_ZOOM_LEVEL = -20;
public static final int DEFAULT_MAX_ZOOM_LEVEL = 10;
public static final double DEFAULT_ZOOM_MULTIPLICATION_FACTOR = 1.2;

private Component targetComponent;

private int zoomLevel = 0;
private int minZoomLevel = DEFAULT_MIN_ZOOM_LEVEL;
private int maxZoomLevel = DEFAULT_MAX_ZOOM_LEVEL;
private double zoomMultiplicationFactor = DEFAULT_ZOOM_MULTIPLICATION_FACTOR;

private Point dragStartScreen;
private Point dragEndScreen;
private AffineTransform coordTransform = new AffineTransform();

public ZoomAndPanListener(Component targetComponent) {
this.targetComponent = targetComponent;
}

public ZoomAndPanListener(Component targetComponent, int minZoomLevel, int maxZoomLevel, double zoomMultiplicationFactor) {
this.targetComponent = targetComponent;
this.minZoomLevel = minZoomLevel;
this.maxZoomLevel = maxZoomLevel;
this.zoomMultiplicationFactor = zoomMultiplicationFactor;
}


public void mouseClicked(MouseEvent e) {
}

public void mousePressed(MouseEvent e) {
dragStartScreen = e.getPoint();
dragEndScreen = null;
}

public void mouseReleased(MouseEvent e) {
// moveCamera(e);
}

public void mouseEntered(MouseEvent e) {
}

public void mouseExited(MouseEvent e) {
}

public void mouseMoved(MouseEvent e) {
}

public void mouseDragged(MouseEvent e) {
moveCamera(e);
}

public void mouseWheelMoved(MouseWheelEvent e) {
// System.out.println("============= Zoom camera ============");
zoomCamera(e);
}

private void moveCamera(MouseEvent e) {
// System.out.println("============= Move camera ============");
try {
dragEndScreen = e.getPoint();
Point2D.Float dragStart = transformPoint(dragStartScreen);
Point2D.Float dragEnd = transformPoint(dragEndScreen);
double dx = dragEnd.getX() - dragStart.getX();
double dy = dragEnd.getY() - dragStart.getY();
coordTransform.translate(dx, dy);
dragStartScreen = dragEndScreen;
dragEndScreen = null;
targetComponent.repaint();
} catch (NoninvertibleTransformException ex) {
ex.printStackTrace();
}
}

private void zoomCamera(MouseWheelEvent e) {
try {
int wheelRotation = e.getWheelRotation();
Point p = e.getPoint();
if (wheelRotation > 0) {
if (zoomLevel < maxZoomLevel) {
zoomLevel++;
Point2D p1 = transformPoint(p);
coordTransform.scale(1 / zoomMultiplicationFactor, 1 / zoomMultiplicationFactor);
Point2D p2 = transformPoint(p);
coordTransform.translate(p2.getX() - p1.getX(), p2.getY() - p1.getY());
targetComponent.repaint();
}
} else {
if (zoomLevel > minZoomLevel) {
zoomLevel--;
Point2D p1 = transformPoint(p);
coordTransform.scale(zoomMultiplicationFactor, zoomMultiplicationFactor);
Point2D p2 = transformPoint(p);
coordTransform.translate(p2.getX() - p1.getX(), p2.getY() - p1.getY());
targetComponent.repaint();
}
}
} catch (NoninvertibleTransformException ex) {
ex.printStackTrace();
}
}

private Point2D.Float transformPoint(Point p1) throws NoninvertibleTransformException {
// System.out.println("Model -> Screen Transformation:");
// showMatrix(coordTransform);
AffineTransform inverse = coordTransform.createInverse();
// System.out.println("Screen -> Model Transformation:");
// showMatrix(inverse);

Point2D.Float p2 = new Point2D.Float();
inverse.transform(p1, p2);
return p2;
}

private void showMatrix(AffineTransform at) {
double[] matrix = new double[6];
at.getMatrix(matrix); // { m00 m10 m01 m11 m02 m12 }
int[] loRow = {0, 0, 1};
for (int i = 0; i < 2; i++) {
System.out.print("[ ");
for (int j = i; j < matrix.length; j += 2) {
System.out.printf("%5.1f ", matrix[j]);
}
System.out.print("]\n");
}
System.out.print("[ ");
for (int i = 0; i < loRow.length; i++) {
System.out.printf("%3d ", loRow[i]);
}
System.out.print("]\n");
System.out.println("---------------------");
}


public int getZoomLevel() {
return zoomLevel;
}

public void setZoomLevel(int zoomLevel) {
this.zoomLevel = zoomLevel;
}

public AffineTransform getCoordTransform() {
return coordTransform;
}

public void setCoordTransform(AffineTransform coordTransform) {
this.coordTransform = coordTransform;
}
}