i have tow audio files and
i want to join that two audio files using java codding or any java Audio-Sound API.
String wavFile1 = "D://SampleAudio_0.4mb.mp3";
String wavFile2 = "D://wSampleAudio_0.7mb.mp3";
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://merge1.mp3"));
I get the following exception:
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
Got the Solution and It's Working for me.
String wavFile1 = "C:\\1.mp3";
String wavFile2 = "C:\\2.mp3";
FileInputStream fistream1 = new FileInputStream(wavFile1); // first source file
FileInputStream fistream2 = new FileInputStream(wavFile2);//second source file
SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2);
FileOutputStream fostream = new FileOutputStream("D://merge1.mp3");//destinationfile
int temp;
while( ( temp = sistream.read() ) != -1)
{
// System.out.print( (char) temp ); // to print at DOS prompt
fostream.write(temp); // to write to file
}
fostream.close();
sistream.close();
fistream1.close();
fistream2.close();
I think .7mb.mp3 is recognised as a .7mb extension. Make sure that's not causing problems. Try to rename your files this way:
From:
String wavFile1 = "D://SampleAudio_0.4mb.mp3";
String wavFile2 = "D://wSampleAudio_0.7mb.mp3";
To:
String wavFile1 = "D://SampleAudio_01.mp3";
String wavFile2 = "D://wSampleAudio_02.mp3";
Update
I didn't see that you have answered the question already, but I think it's worth keeping on eye on the extensions in the future.
Related
When I execute below code it overwrite the existing file. I want to keep old file and new file too. What can be done here? Can we rename it like Test(1).xlsx, Test(2).xlsx, Test(3).xlsx like windows pattern?
File excel = new File("C:\\TEST\\Test.xlsx");
try (FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);) {
..
..
..
try (FileOutputStream outputStream = new FileOutputStream("C:\\TEST\\Output\\Test.xlsx")) {
book.write(outputStream);
}
}
You can check if the file already exists using the exists() method before you start writing to it.
If the file already exists, write to a different file.
File excel = new File(determineFileName());
try (FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);) {
...
}
with
private String determineFileName(){
String path = "C:\\TEST\\Test.xlsx";
int counter = 0;
while(new File(path).exists()){
counter++;
path = "C:\\TEST\\Test(" + counter + ").xlsx";
}
return path;
}
I want to write a unit test to test creating .zip file from two .doc files. BU I take an error: Error creating zip file: java.io.FileNotFoundException: D:\file1.txt (The system cannot find the file specified)
My code is here:
#Test
public void testIsZipped() {
String actualValue1 = "D:/file1.txt";
String actualValue2 = "D:/file2.txt";
String zipFile = "D:/file.zip";
String[] srcFiles = { actualValue1, actualValue2 };
try {
// create byte buffer
byte[] buffer = new byte[1024];
FileOutputStream fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(fos);
for (int i = 0; i < srcFiles.length; i++) {
File srcFile = new File(srcFiles[i]);
FileInputStream fis = new FileInputStream(srcFile);
// begin writing a new ZIP entry, positions the stream to the
// start of the entry data
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
// close the InputStream
fis.close();
}
// close the ZipOutputStream
zos.close();
}
catch (IOException ioe) {
System.out.println("Error creating zip file: " + ioe);
}
String result = zos.toString();
assertEquals("D:/file.zip", result);
}
Can I get name of zip file from zos to test, How to understand to pass the test? Can anybody help me to solve this error? Thank you.
First, are your files created in a previous test method? If yes consider that junit tests do not execute in the order you defined your test methods, have a look at this:
How to run test methods in specific order in JUnit4?
Second, you could add a debugging line:
File srcFile = new File(srcFiles[i]);
System.out.append(srcFile+ ": " + srcFile.exists() + " " + srcFile.canRead());
After you solve the exception you will run into this problem, the test will fail:
String result = zos.toString();
assertEquals("D:/file.zip", result);
zos.toString() will return something like: "java.util.zip.ZipOutputStream#1ae369b7" which will not be equal to "D:/file.zip".
String zipFile = "D:/file.zip";
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
System.out.println(zos.toString());
I'm trying to read .srt files that are located in zip file itself located in a zip file. I succeed to read .srt files that were in a simple zip with the extract of code below :
for (Enumeration enume = fis.entries(); enume.hasMoreElements();) {
ZipEntry entry = (ZipEntry) enume.nextElement();
fileName = entry.toString().substring(0,entry.toString().length()-4);
try {
InputStream in = fis.getInputStream(entry);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String ext = entry.toString().substring(entry.toString().length()-4, entry.toString().length());
But now i don't know how i could get to the zip file inside the zip file.
I tried using ZipFile fis = new ZipFile(filePath) with filePath being the path of the zip file + the name of zip file inside. It didn't recognize the path so i don't know if i am clear.
Thanks.
ZipFile only works with real files, because it's intended for use as a random access mechanism which needs to be able to seek directly to specific locations in the file to read entries by name. But as VGR suggests in the comments, while you can't get random access to the zip-inside-a-zip you can use ZipInputStream, which provides strictly sequential access to the entries and works with any InputStream of zip-format data.
However, ZipInputStream has a slightly odd usage pattern compared to other streams - calling getNextEntry reads the entry metadata and positions the stream to read that entry's data, you read from the ZipInputStream until it reports EOF, then you (optionally) call closeEntry() before moving on to the next entry in the stream.
The critical point is that you must not close() the ZipInputStream until you have finished reading the final entry, so depending what you want to do with the entry data you might need to use something like the commons-io CloseShieldInputStream to guard against the stream getting closed prematurely.
try(ZipInputStream outerZip = new ZipInputStream(fis)) {
ZipEntry outerEntry = null;
while((outerEntry = outerZip.getNextEntry()) != null) {
if(outerEntry.getName().endsWith(".zip")) {
try(ZipInputStream innerZip = new ZipInputStream(
new CloseShieldInputStream(outerZip))) {
ZipEntry innerEntry = null;
while((innerEntry = innerZip.getNextEntry()) != null) {
if(innerEntry.getName().endsWith(".srt")) {
// read the data from the innerZip stream
}
}
}
}
}
}
Find the code to extract .zip files recursively:
public void extractFolder(String zipFile) throws ZipException, IOException {
System.out.println(zipFile);
int BUFFER = 2048;
File file = new File(zipFile);
ZipFile zip = new ZipFile(file);
String newPath = zipFile.substring(0, zipFile.length() - 4);
new File(newPath).mkdir();
Enumeration zipFileEntries = zip.entries();
// Process each entry
while (zipFileEntries.hasMoreElements())
{
// grab a zip file entry
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
File destFile = new File(newPath, currentEntry);
//destFile = new File(newPath, destFile.getName());
File destinationParent = destFile.getParentFile();
// create the parent directory structure if needed
destinationParent.mkdirs();
if (!entry.isDirectory())
{
BufferedInputStream is = new BufferedInputStream(zip
.getInputStream(entry));
int currentByte;
// establish buffer for writing file
byte data[] = new byte[BUFFER];
// write the current file to disk
FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest = new BufferedOutputStream(fos,
BUFFER);
// read and write until last byte is encountered
while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
dest.close();
is.close();
}
if (currentEntry.endsWith(".zip"))
{
// found a zip file, try to open
extractFolder(destFile.getAbsolutePath());
}
}
}
I'm trying to downsample a .wav audio from 22050 to 8000 using AudioInputStream but the conversion returns me 0 data bytes. Here is the code:
AudioInputStream ais;
AudioInputStream eightKhzInputStream = null;
ais = AudioSystem.getAudioInputStream(file);
if (ais.getFormat().getSampleRate() == 22050f) {
AudioFileFormat sourceFileFormat = AudioSystem.getAudioFileFormat(file);
AudioFileFormat.Type targetFileType = sourceFileFormat.getType();
AudioFormat sourceFormat = ais.getFormat();
AudioFormat targetFormat = new AudioFormat(
sourceFormat.getEncoding(),
8000f,
sourceFormat.getSampleSizeInBits(),
sourceFormat.getChannels(),
sourceFormat.getFrameSize(),
8000f,
sourceFormat.isBigEndian());
eightKhzInputStream = AudioSystem.getAudioInputStream(targetFormat, ais);
int nWrittenBytes = 0;
nWrittenBytes = AudioSystem.write(eightKhzInputStream, targetFileType, file);
I already checked AudioSystem.isConversionSupported(targetFormat, sourceFormat) and it returns true. Any idea?
I have just tested your code with different audio files and everything seems to work just fine. I can only guess, that you are either testing your code with an empty audio file (bytes == 0) or, that the file you try to convert is not supported by the Java Audio System.
Try using another input file and/or convert your input file to a compatible file, and it should work.
Here is the main method, that worked for me:
public static void main(String[] args) throws InterruptedException, UnsupportedAudioFileException, IOException {
File file = ...;
File output = ...;
AudioInputStream ais;
AudioInputStream eightKhzInputStream = null;
ais = AudioSystem.getAudioInputStream(file);
AudioFormat sourceFormat = ais.getFormat();
if (ais.getFormat().getSampleRate() == 22050f) {
AudioFileFormat sourceFileFormat = AudioSystem.getAudioFileFormat(file);
AudioFileFormat.Type targetFileType = sourceFileFormat.getType();
AudioFormat targetFormat = new AudioFormat(
sourceFormat.getEncoding(),
8000f,
sourceFormat.getSampleSizeInBits(),
sourceFormat.getChannels(),
sourceFormat.getFrameSize(),
8000f,
sourceFormat.isBigEndian());
if (!AudioSystem.isFileTypeSupported(targetFileType) || ! AudioSystem.isConversionSupported(targetFormat, sourceFormat)) {
throw new IllegalStateException("Conversion not supported!");
}
eightKhzInputStream = AudioSystem.getAudioInputStream(targetFormat, ais);
int nWrittenBytes = 0;
nWrittenBytes = AudioSystem.write(eightKhzInputStream, targetFileType, output);
System.out.println("nWrittenBytes: " + nWrittenBytes);
}
}
I tried creating a pdf file out of another one(in my local drive) using java.io. The thing is a file with a .pdf extension got created but im unable to open the file, it says the file is already in use and most importantly the size of the file is too large and it keeps on increasing (origin file size : 5,777kB and the newly created one file size as of now is 38,567kB). Im not that much of skilled java programmer but still i would appreciate if anyone can give me an explanation ..
String path = "D:\\priya_Docs\\Android pdfs\\Professional_Android_Application_Development.pdf";
File file = new File(path);
System.out.println("Located a file " + file.isFile());
String filesArray = file.getPath();
File getFile = file.getAbsoluteFile();
FileInputStream fis = new FileInputStream(getFile);
FileOutputStream fos = new FileOutputStream(
"D:\\priya_Docs\\Androiddoc.pdf");
for (int b = fis.read(); b != -1;) {
fos.write(b);
}
Simple use,
FileUtils.copyFile()
you meet the two problems
first,you have to close the resource: fis and fos,or it will say the file already in use
second,you have to use the byte[] to receive the data because pdf file is organized in byte arrays
String path = "D:\\priya_Docs\\Android pdfs\\Professional_Android_Application_Development.pdf";
File file = new File(path);
System.out.println("Located a file " + file.isFile());
String filesArray = file.getPath();
File getFile = file.getAbsoluteFile();
FileInputStream fis = new FileInputStream(getFile);
FileOutputStream fos = new FileOutputStream(
"D:\\priya_Docs\\Androiddoc.pdf");
byte[] buff=new byte[1024];
int len;
while((len=fis.read(buff))>=0) {
fos.write(buff,0,len);
}
fis.close();
fos.close();