Evento Docente Universida del Mar

Clase Ventana

/*
UNIVERSIDAD DEL MAR

PROYECTO: CREAR UN SISTEMA QUE REPRODUZCA UNA MELODIA (USANDO LAS NOTAS BASICAS)
CREADA POR EL USUARIO.
AUTORES:

* Eli rafael Galguera Bautista
* Darwin Sosa Gómez
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import javax.swing.event.*;
import javax.sound.midi.*;
import java.util.Vector;
import java.io.File;
import java.io.IOException;

public class VentanaSonido extends JFrame implements ActionListener{
final int PROGRAM = 192;
final int NOTEON = 144;
final int NOTEOFF = 128;
final int SUSTAIN = 64;
final int REVERB = 91;
final int numNotas = 7;
final int numPosiciones = 20;
final int ON = 0, OFF = 1;
final Color jfcBlue = new Color(204, 204, 255);
final Color pink = new Color(255, 175, 175);
Sequencer sequencer;
Sequence sequence;
Synthesizer synthesizer;
Instrument instruments[];
ChannelData channels[];
ChannelData channelData;
Vector keys = new Vector();
Vector whiteKeys = new Vector();
JTable table;
boolean record;
int xPos;
Track track;
long startTime;
RecordFrame recordFrame;
JButton btnDo, btnRe, btnMi, btnFa, btnSol, btnLa, btnSi, recordB ;

JButton btnAnt, btnSig,btnFin, btnInicio, btnBorrar, btnStop, btnPlay, btnRec;
JButton btnPointer;
JPanel panelNotas;
Cuadros cuadros;
Container contenedor;
public VentanaSonido() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
}
super.setTitle("Sistema de archivos Midi");
pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int w = 530;
int h = 270;
setLocation(screenSize.width/2 - w/2, screenSize.height/2 - h/2);
setSize(w, h);
setResizable(false);

contenedor = getContentPane();
contenedor.setLayout(new BorderLayout());

xPos = 0;

recordB = createButton("Record...");
btnRec = createButton("Grabar");
btnDo = createButton("Do");
btnRe = createButton("Re");
btnMi = createButton("Mi");
btnFa = createButton("Fa");
btnSol = createButton("Sol");
btnLa = createButton("La");
btnSi = createButton("Si");
btnAnt=createButton("<<");
btnSig=createButton(">>");
btnFin=createButton(">|");
btnInicio=createButton("|<");
btnBorrar=createButton("X");
btnStop=createButton("O");
btnPlay=createButton(">");
btnPointer = new JButton();
btnPointer.setIcon(new ImageIcon("icono.png"));
btnPointer.setSize(20,20);
btnPointer.setLocation(0,145);


JPanel p1 = new JPanel(new GridLayout(2,8));
p1.add(btnInicio);
p1.add(btnAnt);
p1.add(btnStop);
p1.add(btnBorrar);
p1.add(btnPlay);
p1.add(btnSig);
p1.add(btnFin);
p1.add(recordB);
p1.add(btnSi);
p1.add(btnLa);
p1.add(btnSol);
p1.add(btnFa);
p1.add(btnMi);
p1.add(btnRe);
p1.add(btnDo);

cuadros = new Cuadros(182);
panelNotas=new JPanel(null);
for (int i=0; i<182; i++)
panelNotas.add(cuadros.obtenerBoton(i));
panelNotas.add(btnPointer);
contenedor.add(panelNotas,BorderLayout.CENTER);
contenedor.add(p1,BorderLayout.SOUTH);
setVisible(true);

btnSig.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
btnPointer.setLocation(xPos*20,145);
xPos++;
if(xPos==Configuracion.COLUMNAS){
btnSig.setEnabled(false);
habilitarNotas(false);
}
}
});

}

public void habilitarNotas(boolean habilitar){
btnDo.setEnabled(habilitar);
btnRe.setEnabled(habilitar);
btnMi.setEnabled(habilitar);
btnFa.setEnabled(habilitar);
btnSol.setEnabled(habilitar);
btnLa.setEnabled(habilitar);
btnSi.setEnabled(habilitar);
}

public void actionPerformed(ActionEvent e) {

if(e.getSource().equals(btnDo)){
channelData.channel.noteOn(Notas.DO, channelData.velocity);
if (record) {
creaEventoCorto(NOTEON, Notas.DO);
}
cuadros.mostrar(xPos,Notas._do);
btnSig.doClick();

} else if (e.getSource().equals(btnRe)){
channelData.channel.noteOn(Notas.RE, channelData.velocity);
if (record) {
creaEventoCorto(NOTEON, Notas.RE);
}
cuadros.mostrar(xPos,Notas._re);
btnSig.doClick();
}else if (e.getSource().equals(btnMi)){
channelData.channel.noteOn(Notas.MI, channelData.velocity);
if (record) {
creaEventoCorto(NOTEON, Notas.MI);
}
cuadros.mostrar(xPos,Notas._mi);
btnSig.doClick();
}else if (e.getSource().equals(btnFa)){
channelData.channel.noteOn(Notas.FA, channelData.velocity);
if (record) {
creaEventoCorto(NOTEON, Notas.FA);
}
cuadros.mostrar(xPos,Notas._fa);
btnSig.doClick();
}else if (e.getSource().equals(btnSol)){
channelData.channel.noteOn(Notas.SOL, channelData.velocity);
if (record) {
creaEventoCorto(NOTEON, Notas.SOL);
}
cuadros.mostrar(xPos,Notas._sol);
btnSig.doClick();
}else if (e.getSource().equals(btnLa)){
channelData.channel.noteOn(Notas.LA, channelData.velocity);
if (record) {
creaEventoCorto(NOTEON, Notas.LA);
}
cuadros.mostrar(xPos,Notas._la);
btnSig.doClick();
}else if (e.getSource().equals(btnSi)){
channelData.channel.noteOn(Notas.SI, channelData.velocity);
if (record) {
creaEventoCorto(NOTEON, Notas.SI);
}
cuadros.mostrar(xPos,Notas._si);
btnSig.doClick();
}

JButton button = (JButton) e.getSource();
if (button.getText().startsWith("Record")) {
if (recordFrame != null) {
recordFrame.toFront();
} else {
recordFrame = new RecordFrame();
}
}
}
public JButton createButton(String name) {
JButton b = new JButton(name);
b.addActionListener(this);
contenedor.add(b);
return b;
}
public void open() {
try {
if (synthesizer == null) {
if ((synthesizer = MidiSystem.getSynthesizer()) == null) {
System.out.println("getSynthesizer() failed!");
return;
}
}
synthesizer.open();
sequencer = MidiSystem.getSequencer();
sequence = new Sequence(Sequence.PPQ, 10);
} catch (Exception ex) { ex.printStackTrace(); return; }

Soundbank sb = synthesizer.getDefaultSoundbank();
if (sb != null) {
instruments = synthesizer.getDefaultSoundbank().getInstruments();
synthesizer.loadInstrument(instruments[0]);
}
MidiChannel midiChannels[] = synthesizer.getChannels();
channels = new ChannelData[midiChannels.length];
for (int i = 0; i < channels.length; i++) {
channels[i] = new ChannelData(midiChannels[i], i);
}
channelData = channels[0];
}

public void close() {
if (synthesizer != null) {
synthesizer.close();
}
if (sequencer != null) {
sequencer.close();
}
sequencer = null;
synthesizer = null;
instruments = null;
channels = null;
if (recordFrame != null) {
recordFrame.dispose();
recordFrame = null;
}
}

public void creaEventoCorto(int type, int num) {
ShortMessage mensajeCorto = new ShortMessage();
try {
long millis = System.currentTimeMillis() - startTime;
long tick = millis * sequence.getResolution() / 500;
mensajeCorto.setMessage(type+channelData.num, num, channelData.velocity);
MidiEvent event = new MidiEvent(mensajeCorto, tick);
track.add(event);
} catch (Exception ex) { ex.printStackTrace(); }
}

/*************************************************************************************************/
class ChannelData {

MidiChannel channel;
boolean solo, mono, mute, sustain;
int velocity = 127;
int pressure = 127;
int bend = 16383;
int reverb = 127;
int row, col, num;

public ChannelData(MidiChannel channel, int num) {
this.channel = channel;
this.num = num;
}

public void setComponentStates() {
table.setRowSelectionInterval(row, row);
table.setColumnSelectionInterval(col, col);
}
}

class RecordFrame extends JFrame implements ActionListener, MetaEventListener {
public JButton recB, playB, saveB;
Vector tracks = new Vector();
DefaultListModel listModel = new DefaultListModel();
TableModel dataModel;

public RecordFrame() {
super("Grabando Archivo Midi");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {recordFrame = null;}
});

sequencer.addMetaEventListener(this);
try {
sequence = new Sequence(Sequence.PPQ, 10);
} catch (Exception ex) { ex.printStackTrace(); }

JPanel p1 = new JPanel(new BorderLayout());

JPanel p2 = new JPanel();
p2.setBorder(new EmptyBorder(5,5,5,5));
p2.setLayout(new BoxLayout(p2, BoxLayout.X_AXIS));

recB = createButton("Record", p2, true);
playB = createButton("Play", p2, false);
saveB = createButton("Save...", p2, false);
getContentPane().add("North", p2);

pack();
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int w = 220;
int h = 80;
setLocation(d.width/2 - w/2, d.height/2 - h/2);
setSize(w, h);
setResizable(false);
setVisible(true);
}

public JButton createButton(String name, JPanel p, boolean state) {
JButton b = new JButton(name);
b.setFont(new Font("serif", Font.PLAIN, 10));
b.setEnabled(state);
b.addActionListener(this);
p.add(b);
return b;
}

public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button.equals(recB)) {
record = recB.getText().startsWith("Record");
if (record) {
track = sequence.createTrack();
startTime = System.currentTimeMillis();
creaEventoCorto(PROGRAM,channelData.col*8+channelData.row);

recB.setText("Stop");
playB.setEnabled(false);
saveB.setEnabled(false);
} else {
String name = null;
if (instruments != null) {
name = instruments[channelData.col*8+channelData.row].getName();
} else {
name = Integer.toString(channelData.col*8+channelData.row);
}
tracks.add(new TrackData(channelData.num+1, name, track));
recB.setText("Record");
playB.setEnabled(true);
saveB.setEnabled(true);
}
} else if (button.equals(playB)) {
if (playB.getText().startsWith("Play")) {
try {
sequencer.open();
sequencer.setSequence(sequence);
} catch (Exception ex) { ex.printStackTrace(); }
sequencer.start();
playB.setText("Stop");
recB.setEnabled(false);
} else {
sequencer.stop();
playB.setText("Play");
recB.setEnabled(true);
}
} else if (button.equals(saveB)) {
try {
File file = new File(System.getProperty("user.dir"));
JFileChooser fc = new JFileChooser(file);
fc.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
return false;
}
public String getDescription() {
return "Guardar como archivo .mid";
}
});
if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
saveMidiFile(fc.getSelectedFile());
}
} catch (SecurityException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public void meta(MetaMessage message) {
if (message.getType() == 47) {
playB.setText("Play");
recB.setEnabled(true);
}
}

public void saveMidiFile(File file) {
try {
int[] fileTypes = MidiSystem.getMidiFileTypes(sequence);
if (fileTypes.length == 0) {
System.out.println("No se puede guardar la secuencia");
} else {
if (MidiSystem.write(sequence, fileTypes[0], file) == -1) {
throw new IOException("Error: No se puede guardar el archivo");
}
}
} catch (SecurityException ex) {
} catch (Exception ex) {
ex.printStackTrace();
}
}

class TrackData extends Object {
Integer chanNum; String name; Track track;
public TrackData(int chanNum, String name, Track track) {
this.chanNum = new Integer(chanNum);
this.name = name;
this.track = track;
}
}
}
/***********************************************************************************/

public static void main(String args[]) {
VentanaSonido ventana = new VentanaSonido();
ventana.open();
ventana.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {

System.exit(0);}
});
}
}

Tags:

0 comentarios: