mardi 30 décembre 2014

How do I edit a recorded wav file format in java?

Hi I am developing an audio that allows me to record play and edit audio in wave format, I managed to record and play but still I have found no way to edit these once already saved or recorded files, I tried to do to travez of a byte array but I only managed to insert audio at the beginning and end of nomas file, Here I give you my code, Sorry if I do not write properly because my English is very bad



public class GrabadorAudio extends javax.swing.JDialog {

private ControladorAudio controladorAudio;
AudioFormat audioFormat;
TargetDataLine targetDataLine;
TargetDataLine targetDataLine2;
int tamañoAudio;
File audioFile = null;
File yourFile=null;
File copia=null;
Timer timer;
Clip clip;
Capture capturar;
int audioPosicion;
boolean controlPausa=false;
boolean controlStop=false;
boolean controlPlay= false;
boolean controlInicio=false;
boolean controlFin= false;
boolean controlGrabar=false;
boolean controlResume=false;
CaptureThread cap;
AudioFileFormat.Type fileType = null;
double durationInSeconds;
byte[] datatec=null;
byte[] datatec2=null;
long frames;
int prueba=0;
AudioInputStream audioInputStream;

private String ext="wav";

String directorio;


public GrabadorAudio(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
setLocationRelativeTo(this);
controladorAudio= new ControladorAudio();
Btnguardar.setEnabled(false);
Btnplay.setEnabled(false);
Btninicio.setEnabled(false);
Btnfin.setEnabled(false);
Btnpause.setEnabled(false);
Sliprogreso.setEnabled(false);

timer= new Timer();
capturar= new Capture();
Properties p = System.getProperties();
directorio=p.getProperty("user.home");
fileType = AudioFileFormat.Type.WAVE;

audioFile = new File(directorio+"/.vmaudio/audio1."+ext);
}

@SuppressWarnings("unchecked")

private void initComponents() {

PanelGrabador = new javax.swing.JPanel();
Btnplay = new javax.swing.JButton();
Btngrabar = new javax.swing.JButton();
Btnguardar = new javax.swing.JButton();
Btninicio = new javax.swing.JButton();
Btnfin = new javax.swing.JButton();
Sliprogreso = new javax.swing.JSlider();
Lbltiempo = new javax.swing.JLabel();
Btnsalir = new javax.swing.JButton();
Btnpause = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

Btnplay.setText("Play/Stop");
Btnplay.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnplayActionPerformed(evt);
}
});

Btngrabar.setText("Rec");
Btngrabar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtngrabarActionPerformed(evt);
}
});

Btnguardar.setText("Guardar");
Btnguardar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnguardarActionPerformed(evt);
}
});

Btninicio.setText("inicio");
Btninicio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtninicioActionPerformed(evt);
}
});

Btnfin.setText("fin");
Btnfin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnfinActionPerformed(evt);
}
});

Sliprogreso.setMajorTickSpacing(1);
Sliprogreso.setMaximum(10);
Sliprogreso.setPaintLabels(true);
Sliprogreso.setPaintTicks(true);
Sliprogreso.setToolTipText("");
Sliprogreso.setValue(0);
Sliprogreso.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
SliprogresoStateChanged(evt);
}
});

Btnsalir.setText("Salir");
Btnsalir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnsalirActionPerformed(evt);
}
});

Btnpause.setText("Pause/Resume");
Btnpause.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnpauseActionPerformed(evt);
}
});

javax.swing.GroupLayout PanelGrabadorLayout = new javax.swing.GroupLayout(PanelGrabador);
PanelGrabador.setLayout(PanelGrabadorLayout);
PanelGrabadorLayout.setHorizontalGroup(
PanelGrabadorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PanelGrabadorLayout.createSequentialGroup()
.addGap(110, 110, 110)
.addComponent(Btninicio)
.addGap(105, 105, 105)
.addComponent(Btnfin)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 114, Short.MAX_VALUE)
.addGroup(PanelGrabadorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PanelGrabadorLayout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(Btnsalir))
.addComponent(Lbltiempo, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(34, 34, 34))
.addGroup(PanelGrabadorLayout.createSequentialGroup()
.addGroup(PanelGrabadorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PanelGrabadorLayout.createSequentialGroup()
.addGap(51, 51, 51)
.addComponent(Btnplay)
.addGap(18, 18, 18)
.addComponent(Btnpause)
.addGap(31, 31, 31)
.addComponent(Btngrabar, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(42, 42, 42)
.addComponent(Btnguardar))
.addGroup(PanelGrabadorLayout.createSequentialGroup()
.addGap(67, 67, 67)
.addComponent(Sliprogreso, javax.swing.GroupLayout.PREFERRED_SIZE, 437, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
PanelGrabadorLayout.setVerticalGroup(
PanelGrabadorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PanelGrabadorLayout.createSequentialGroup()
.addGap(32, 32, 32)
.addGroup(PanelGrabadorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Btnplay)
.addComponent(Btngrabar)
.addComponent(Btnguardar)
.addComponent(Btnpause))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 62, Short.MAX_VALUE)
.addComponent(Sliprogreso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Lbltiempo, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(PanelGrabadorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PanelGrabadorLayout.createSequentialGroup()
.addGap(9, 9, 9)
.addComponent(Btninicio))
.addGroup(PanelGrabadorLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(PanelGrabadorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Btnsalir)
.addComponent(Btnfin))))
.addGap(71, 71, 71))
);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(PanelGrabador, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(PanelGrabador, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);

pack();
}// </editor-fold>


private void BtnplayActionPerformed(java.awt.event.ActionEvent evt) {
if(controlStop){
Btnplay.setText("Play");
Btnpause.setEnabled(false);
controlPausa=false;
controlStop=false;
capturar.stop();
Btngrabar.setEnabled(true);
Btnplay.setEnabled(true);
Btnfin.setEnabled(true);
Btninicio.setEnabled(true);



}
else{


Btnpause.setEnabled(true);
controlPlay=true;
Sliprogreso.setEnabled(true);
try {
AudioInputStream stream;
AudioFormat format;
DataLine.Info info;

yourFile = new File(directorio+"/.vmaudio/audio1.wav");

stream = AudioSystem.getAudioInputStream(yourFile);


format = stream.getFormat();


frames =stream.getFrameLength();
durationInSeconds = (frames+0.0) / format.getFrameRate();


System.out.println("duracion:"+durationInSeconds);
Sliprogreso.setMaximum((int) durationInSeconds);


info = new DataLine.Info(Clip.class, format);


clip = (Clip) AudioSystem.getLine(info);
clip.open(stream);
clip.start();



TimerTask timerTask=new TimerTask(){
public synchronized void run() {
{
double timeNow=(durationInSeconds*clip.getFramePosition())/frames;
Sliprogreso.setValue((int)Math.round(timeNow));
if((int)Math.round(timeNow)==(int)durationInSeconds){
System.out.println("se cancelo");
this.cancel();}
}

}
};


}



catch (Exception e) {
System.out.println(e);

e.printStackTrace();

}

}

}

private void BtngrabarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
controlPausa=true;
controlGrabar=true;
controlStop=true;
Btnpause.setText("Pause");
Btnplay.setText("Stop");
Btnpause.setEnabled(true);
Btnplay.setEnabled(true);


final SwingWorker worker= new SwingWorker() {

@Override
protected Object doInBackground() throws Exception {
try{
capturar.start();
Btngrabar.setEnabled(false);

}catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
protected void done() {


}

};

worker.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent pce) {
// progressBar.setValue(progreso);//actualizamos el valor del progressBar
}
});



worker.execute();
}

private void BtninicioActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Sliprogreso.setValue(0);
}

private void BtnfinActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Sliprogreso.setValue(10);
}

private void SliprogresoStateChanged(javax.swing.event.ChangeEvent evt) {
// TODO add your handling code here:



}

private void BtnsalirActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:

System.exit(0);
}

private void BtnguardarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}

private void BtnpauseActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String pause=Btnpause.getText();

if(controlPausa){

controlPausa=false;
controlResume=true;
capturar.line.stop();
Btngrabar.setEnabled(false);
Btnplay.setEnabled(false);
Btnpause.setText("Resume");
System.out.println(" entro al controlpausa");

} else{
if(controlPlay){
controlPlay=false;
Btnpause.setText("Resume");
Btnplay.setEnabled(false);
clip.stop();


}
else{
if (controlResume){

Btnpause.setText("Pause");
Btnplay.setEnabled(true);
controlStop=true;
capturar.line.start();
}
else{
clip.start();
Btnpause.setText("Pause");
controlPlay=true;
}


}





}

}

private AudioFormat getAudioFormat(){

float sampleRate = 4000.0F;

int sampleSizeInBits = 8;

int channels = 1;

boolean signed = true;

boolean bigEndian = false;

return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed,
bigEndian);

}



class CaptureThread extends Thread{
public synchronized void run(){
fileType = AudioFileFormat.Type.WAVE;
audioFile = new File(directorio+"/.vmaudio/audio1."+ext);

try{
targetDataLine.open(audioFormat);
targetDataLine.start();
AudioSystem.write(
new AudioInputStream(targetDataLine),
fileType,
audioFile);


}catch (Exception e){
e.printStackTrace();
}


}



}

class Capture implements Runnable {

TargetDataLine line;

Thread thread;


public void start() {
thread = new Thread(this);
thread.setName("Capture");
thread.start();

}

public void stop() {

thread = null;

}



public void run() {


audioInputStream = null;



AudioFormat format = getAudioFormat();
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

if (!AudioSystem.isLineSupported(info)) {
// shutDown("Line matching " + info + " not supported.");
return;
}

// get and open the target data line for capture.

try {

line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format, line.getBufferSize());

} catch (LineUnavailableException ex) {

ex.printStackTrace();
return;

} catch (SecurityException ex) {

ex.printStackTrace();
return;

} catch (Exception ex) {

ex.printStackTrace();
return;
}

// play back the captured audio data
ByteArrayOutputStream out = new ByteArrayOutputStream();
int frameSizeInBytes = format.getFrameSize();
int bufferLengthInFrames = line.getBufferSize() / 8;
int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
byte[] data = new byte[bufferLengthInBytes];



int numBytesRead;

line.start();

while (thread != null) {
if ((numBytesRead = line.read(data, 0, bufferLengthInBytes)) == -1) {
break;
}
out.write(data, 0, numBytesRead);
}

line.stop();
line.close();
line = null;

// stop and close the output stream
try {
out.flush();
out.close();

} catch (Exception ex) {


ex.printStackTrace();
}

// load bytes into the audio input stream for playback
byte audioBytes[] = out.toByteArray();

try{
System.out.println("tamaño de audiobytes"+audioBytes.length);
if (prueba==0){

//datatec=data;
}
int j=0;
int tamañodatatec=0;
if(datatec==null){
tamañodatatec=0;
}
else{
tamañodatatec=datatec.length;
}

for(int i=0;i<audioBytes.length;i++){

if(prueba==1){
datatec= appendData(datatec, audioBytes[i]);
}

}

if (prueba==0){

datatec=out.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(audioBytes);
audioInputStream = new AudioInputStream(bais, format,
audioBytes.length / frameSizeInBytes);
prueba=1;
}else{

ByteArrayInputStream bais = new ByteArrayInputStream(datatec);
audioInputStream = new AudioInputStream(bais, format,
datatec.length / frameSizeInBytes);
}

}catch (Exception e){
e.printStackTrace();
}



try {

AudioSystem.write(audioInputStream, fileType, audioFile);

} catch (Exception ex) {

ex.printStackTrace();
}

try {

audioInputStream.reset();

} catch (Exception ex) {
ex.printStackTrace();
return;
}


}
} // End class Capture


protected byte[] appendData(byte firstObject,byte[] secondObject){
byte[] byteArray= {firstObject};
return appendData(byteArray,secondObject);

}

protected byte[] appendData(byte[] firstObject,byte secondByte){
byte[] byteArray= {secondByte};
return appendData(firstObject,byteArray);

}

protected byte[] appendData(byte[] firstObject,byte[] secondObject){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
if (firstObject!=null && firstObject.length!=0){
outputStream.write(firstObject);
}
if (secondObject!=null && secondObject.length!=0){
outputStream.write(secondObject);
}

} catch (IOException e) {
e.printStackTrace();
}
return outputStream.toByteArray();
}

Aucun commentaire:

Enregistrer un commentaire