Android combine two audio files into one - java

I have two .3gp (or .wav) audio files that I have saved from the user's microphone. How can I concatenate these two audio files together in code into a single file? Thanks.

combining two wav files:
import java.io.File;
import java.io.IOException;
import java.io.SequenceInputStream;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
public class WavAppender {
public static void main(String[] args) {
String wavFile1 = "D:\\wav1.wav";
String wavFile2 = "D:\\wav2.wav";
try {
AudioInputStream clip1 = AudioSystem.getAudioInputStream(new File(wavFile1));
AudioInputStream clip2 = AudioSystem.getAudioInputStream(new File(wavFile2));
AudioInputStream appendedFiles =
new AudioInputStream(
new SequenceInputStream(clip1, clip2),
clip1.getFormat(),
clip1.getFrameLength() + clip2.getFrameLength());
AudioSystem.write(appendedFiles,
AudioFileFormat.Type.WAVE,
new File("D:\\wavAppended.wav"));
} catch (Exception e) {
e.printStackTrace();
}
}
}

Related

Can i take a screenshot and paste it in a word file in appium using Java?

I'm currently using the below method to take screenshots and store them in a folder called 'Screenshots'. But what i want is, to take these screenshots and paste them in a word document according to the test cases to which they belong.
Is it possible? If so could somebody please guide me?
public String FailureScreenshotAndroid(String name) {
try {
Date d = new Date();
String date = d.toString().replace(":", "_").replace(" ", "_");
TakesScreenshot t = (TakesScreenshot)driver;
File f1 = t.getScreenshotAs(OutputType.FILE);//Temporary Location
String permanentLocation =System.getProperty("user.dir")+ "\\Screenshots\\"+name+date+".png";
File f2 = new File(permanentLocation);
FileUtils.copyFile(f1, f2);
return permanentLocation;
}catch (Exception e) {
String msg = e.getMessage();
return msg;
}
}
Try below:
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class TakeScreenshots {
public static void main(String[] args) {
try {
XWPFDocument docx = new XWPFDocument();
XWPFRun run = docx.createParagraph().createRun();
FileOutputStream out = new FileOutputStream("d:/xyz/doc1.docx");
for (int counter = 1; counter <= 5; counter++) {
captureScreenShot(docx, run, out);
TimeUnit.SECONDS.sleep(1);
}
docx.write(out);
out.flush();
out.close();
docx.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void captureScreenShot(XWPFDocument docx, XWPFRun run, FileOutputStream out) throws Exception {
String screenshot_name = System.currentTimeMillis() + ".png";
BufferedImage image = new Robot()
.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
File file = new File("d:/xyz/" + screenshot_name);
ImageIO.write(image, "png", file);
InputStream pic = new FileInputStream("d:/xyz/" + screenshot_name);
run.addBreak();
run.addPicture(pic, XWPFDocument.PICTURE_TYPE_PNG, screenshot_name, Units.toEMU(350), Units.toEMU(350));
pic.close();
file.delete();
}
}

How to start a sound that is already playing?

I'm making game extension to play some sounds. The sounds may be triggered at random times, which means that the same sound may be triggered twice with very little time apart. In this case, the sound should start playing even though it is already playing (if that makes sense).
I'm using a Clip to play the sound. This means that I have to "rewind" the clip before playing it. It seems, since it's the same clip, that it stops playing before re-starting. What I want is for it to continue playing, and play the same clip "on top" of the previos one. See this example:
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class JavaApplication {
public static void main(String[] args) throws Exception {
File file = new File(JavaApplication.class.getResource("1.wav").getPath());
AudioInputStream inputStream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(inputStream);
clip.setFramePosition(0);
clip.start(); // The sound is 300 ms long
Thread.sleep(150); // Let it play for 150 ms
clip.setFramePosition(0); // Attempt to start it from the beginning, without stopping it
clip.start();
Thread.sleep(1000);
}
}
Have you tried creating a duplicate object when you need it and destroy it when it's finished? A new Clip object or just copy the original and get it to play along with it.
Clip temp = clip;
temp.start(); // The sound is 300 ms long
Thread.sleep(150); // Let it play for 150 ms
temp = null;
Just a suggestion, you could also try using Clip[] arrays to handle a few clips playing at different times.
You need to create two AudioInputStream instances. No need to use multi thread exlicitly in your code. Hop it will help. Thanks.
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class JavaApplication {
public static void main(String[] args) throws Exception {
File file = new File(JavaApplication.class.getResource("1.wav").getPath());
AudioInputStream inputStream1 = AudioSystem.getAudioInputStream(file);
AudioInputStream inputStream2 = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(inputStream1);
clip.setFramePosition(0);
clip.start();
// Clip is 2000 ms long. let it play for 1000 ms
Thread.sleep(1000);
Clip clip2 = AudioSystem.getClip();
clip2.open(inputStream2);
clip2.setFramePosition(0);
clip2.start();
Thread.sleep(2000);
}
}
Found a solution: Read the raw bytes of the sound, and create a inputstream from the data each time I play the sound. This enables me to play the same sound file "on top of itself" without loading it from disk more than once.
package com.mysite.javaapplication;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class JavaApplication {
private static void playSoundBytes(byte[] data) throws Exception {
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new ByteArrayInputStream(data));
AudioFormat format = inputStream.getFormat();
Clip clip = AudioSystem.getClip();
clip.open(inputStream);
clip.setFramePosition(0);
clip.start();
}
private static byte[] getResourceAsBytes(String name, int bufferSize) throws IOException {
InputStream stream = JavaApplication.class.getResourceAsStream(name);
byte buffer[] = new byte[bufferSize];
int b, i = 0;
while ((b = stream.read()) != -1) {
try {
buffer[i++] = (byte) b;
} catch (IndexOutOfBoundsException e) {
throw new IOException("Buffer of " + bufferSize + " bytes is too small to read resource \"" + name + "\"");
}
}
byte data[] = new byte[i + 1];
while (i >= 0) {
data[i] = buffer[i];
i--;
}
return data;
}
public static void main(String[] args) throws Exception {
byte[] soundData = getResourceAsBytes("/1.wav", 1000*1000);
playSoundBytes(soundData);
Thread.sleep(1000);
playSoundBytes(soundData);
Thread.sleep(2000);
}
}

I'm trying to lock file exclusively on read

I'm trying to lock a file exclusively on read.
I am using Java 7 on Windows 7.
The files are copied to a directory, and then I want to to read them correctly after copy. That's why I'm trying lock file exclusively on read.
But my program read file in the middle.
Can anyone please help me with this? Thanks!
package test;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
public class FileLockMove {
public static void main(String[] args) {
FileSystem fs = FileSystems.getDefault();
File dir = new File("c:/test_source/");
while(true){
for (File file : dir.listFiles()) {
try (FileChannel fc = (new RandomAccessFile(file, "rw")).getChannel()){
FileLock lock = fc.tryLock();
if(lock != null){
System.out.println("lock is not null\t" + file.getName());
System.out.println("addBody: " + file.getAbsolutePath() + "\t" + file.length());
}else{
System.out.println("lock is null\t" + file.getName());
continue;
}
} catch (Exception e) {
System.out.println("fail:" + file.getName()+"\t" + e.getMessage());
}
try {
Files.move(file.toPath(), fs.getPath("c:/test_dest/",file.getName()));
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Originally, the copy file is not Java, but I created a copy of my program slowly to confirm that I can lock exclusively.
package test;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
public class FileCopySlow{
public static void main(String[] args) {
String source = "C:/test_orig/";
String dst ="C:/test_source/";
File file = new File(source);
File[] files = file.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
if(name.matches(".*\\.bmp")){
return true;
}
return false;
}
});
for(File f: files){
copyStream(f, dst);
}
}
static void copyStream(File source,String dst){
try(BufferedInputStream br = new BufferedInputStream(new FileInputStream(source))){
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dst+source.getName()));
byte[] buff = new byte[100];
int len = -1;
while((len = br.read(buff)) >-1){
out.write(buff,0,len);
out.flush();
Thread.sleep(100);
}
out.close();
System.out.println(source.getName() + "\tfinish");
}catch(Exception e){
e.printStackTrace();
}
}
}

Converting doc into PDF in android,Unable to execute dex

I am converting doc file into pdf format in android using following libraries,
itext-1.4.8.jar
poi-3.0-FINAL.jar
poi-scratchpad-3.2-FINAL.jar
here is my sample code
package com.example.converter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.content.Context;
import android.os.Environment;
import android.widget.LinearLayout;
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class TestCon extends LinearLayout {
FileInputStream infile;
private static String FILE = Environment.getExternalStorageDirectory()
+ "/MyReport.pdf";
public TestCon(Context context) {
super(context);
my_method(context);
}
public void my_method(Context context) {
POIFSFileSystem fs = null;
Document document = new Document();
try {
infile = (FileInputStream) context.getApplicationContext().getAssets().open("test.doc");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
System.out.println("Starting the test");
fs = new POIFSFileSystem(infile);
HWPFDocument doc = new HWPFDocument(fs);
WordExtractor we = new WordExtractor(doc);
OutputStream file = new FileOutputStream(FILE);
PdfWriter writer = PdfWriter.getInstance(document, file);
Range range = doc.getRange();
document.open();
writer.setPageEmpty(true);
document.newPage();
writer.setPageEmpty(true);
String[] paragraphs = we.getParagraphText();
for (int i = 0; i < paragraphs.length; i++) {
org.apache.poi.hwpf.usermodel.Paragraph pr = range
.getParagraph(i);
// CharacterRun run = pr.getCharacterRun(i);
// run.setBold(true);
// run.setCapitalized(true);
// run.setItalic(true);
paragraphs[i] = paragraphs[i].replaceAll("\\cM?\r?\n", "");
System.out.println("Length:" + paragraphs[i].length());
System.out.println("Paragraph" + i + ": "
+ paragraphs[i].toString());
// add the paragraph to the document
document.add(new Paragraph(paragraphs[i]));
}
System.out.println("Document testing completed");
} catch (Exception e) {
System.out.println("Exception during test");
e.printStackTrace();
} finally {
// close the document
document.close();
}
}
}
but I am getting this error
[2013-05-10 12:39:12 - Dex Loader] Unable to execute dex: Multiple dex files define Lorg/apache/poi/generator/FieldIterator;
[2013-05-10 12:39:12 - converter] Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lorg/apache/poi/generator/FieldIterator;
I have removed my android-support-v4.jar. from lib folder a/c to this answer answer about the error but I am still getting the same error :(
Please help me to solve this issue
Anyone who have done the doc to pdf conversion,please share your code.
I will be very thankful :)
Regards
The problem is that you are including something twice or more :
Multiple dex files define Lorg/apache/poi/generator/FieldIterator
Review your build path for duplicated libraries.
In addition, once this is resolved, you'll problably have to add this line in the project.properties file :
dex.force.jumbo=true
This will allow you to solve the problem with the 65535 methods limit problem for some time.

Saving part of an audio file (Java)

While playing an audio file (.wav) I want, if I resort to Ctrl+C, to stop the playback and save part of the audio file in a file called "file2.wav".
Here's the thread I'd like to add to my code.
Unfortunately it doesn't work at all.
class myThread extends Thread{
public void run(){
try {
PipedOutputStream poStream = new PipedOutputStream();
PipedInputStream piStream = new PipedInputStream();
poStream.connect(piStream);
File cutaudioFile = new File ("file2.wav");
AudioInputStream ais =
new AudioInputStream(piStream,
AudioFileFormat.Type.WAVE,
cutaudioFile);
poStream.write(ais,AudioFileFormat.Type.WAVE,cutaudioFile);
}catch (Exception e){
e.printStackTrace();
}
} // end run
} // end myThread
This should be basically what you want. It uses a shutdown hook.
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.sound.sampled.Clip;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class CtrlCAudio
{
public static void main(String[] args) throws LineUnavailableException, UnsupportedAudioFileException, IOException
{
final File inputAudio = new File(args[0]);
final File outputAudio = new File(args[1]);
// First, we get the format of the input file
final AudioFileFormat.Type fileType = AudioSystem.getAudioFileFormat(inputAudio).getType();
// Then, we get a clip for playing the audio.
final Clip c = AudioSystem.getClip();
// We get a stream for playing the input file.
AudioInputStream ais = AudioSystem.getAudioInputStream(inputAudio);
// We use the clip to open (but not start) the input stream
c.open(ais);
// We get the format of the audio codec (not the file format we got above)
final AudioFormat audioFormat = ais.getFormat();
// We add a shutdown hook, an anonymous inner class.
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
// We're now in the hook, which means the program is shutting down.
// You would need to use better exception handling in a production application.
try
{
// Stop the audio clip.
c.stop();
// Create a new input stream, with the duration set to the frame count we reached. Note that we use the previously determined audio format
AudioInputStream startStream = new AudioInputStream(new FileInputStream(inputAudio), audioFormat, c.getLongFramePosition());
// Write it out to the output file, using the same file type.
AudioSystem.write(startStream, fileType, outputAudio);
}
catch(IOException e)
{
e.printStackTrace();
}
}
});
// After setting up the hook, we start the clip.
c.start();
}
}

Categories

Resources