Extracting files from Oracle blob fields; - java

I am trying to extract a file from a blob using the values found in the fields following the blob column. My solution works, but it is rather slow.
I extracted 169MB(727 different files) in about 1 hour. That's about 12 files a minute.
most of the files are usually between 5KB and 50KB but can sometimes be as big as 2MB. I am working with a local Oracle database.
Is there anything I could do to make my code more efficient? If not, what other factors might affect the speed of the process? Here is the method's code:
public void beginExtraction(String FileOutDir, String blobSQL,
String fileSuffix, Connection conn) {
if ((FileOutDir != null) && (blobSQL != null) && (conn != null)) {
PreparedStatement selBlobs = null;
FileOutputStream fos = null;
if (conn != null) {
if (blobSQL != null) {
try {
selBlobs = conn.prepareStatement(blobSQL);
ResultSet rs = selBlobs.executeQuery();
int cols = rs.getMetaData().getColumnCount();
while (rs.next()) {
Blob blob = rs.getBlob(1);
InputStream is = blob.getBinaryStream();
String filepath = "";
filepath += FileOutDir + "/";
for (int c = 2; c <= cols; c++) {
filepath += rs.getObject(c).toString() + "_";
}
filepath = filepath.substring(0,
filepath.length() - 1);
filepath += fileSuffix;
fos = new FileOutputStream(filepath);
int b = 0;
while ((b = is.read()) != -1) {
fos.write(b);
}
}
selBlobs.close();
fos.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(gui, e.toString());
}
}
}
} else {
if (conn == null) {
JOptionPane.showMessageDialog(gui,
"You have not selected a database.");
} else {
if (FileOutDir == null) {
JOptionPane.showMessageDialog(gui,
"You have not chosen a directory for your files.");
} else {
if (blobSQL == null) {
JOptionPane.showMessageDialog(gui,
"Please insert an SQL statement.");
}
}
}
}
}

Changing to a buffered output made the process exponentially faster. I was able to export the 727 files in under a minute. Here the new code:
//...
while (rs.next()) {
blob = rs.getBlob(1);
is = blob.getBinaryStream();
filepath += "/";
for (int c = 2; c <= cols; c++) {
filepath += rs.getObject(c).toString() + "_";
}
filepath = filepath.substring(0,
filepath.length() - 1);
filepath += fileSuffix;
fos = new BufferedOutputStream(new FileOutputStream(filepath));
while ((b = is.read()) != -1) {
fos.write(b);
}
filepath = FileOutDir;
b = 0;
}
//...

Related

how to get the original size of the image in java

I have tried to get the size of the image by .length in java.
However the original size of the image is several bytes higher than that.
What is the reason for this? Is there any code to get the original size?
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import javax.imageio.ImageIO;
public class Array {
public static void main(String argv[]) throws IOException {
String imageFile1 = "C:/Users/Desktop/4.jpg";
File file = new File(imageFile1);
BufferedImage originalImage = ImageIO.read(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(originalImage, "jpg", baos);
byte[] imageInByte = baos.toByteArray();
System.out.println("The length in bytes " + imageInByte.length);
}
}
I think it's about jpeg file header size.
If you want to get an original size when copying image file.
You can use just file copy rather then image file copy.
Or, you can make your own jpeg library, if you really want.
For just one example,
this is one of the old-style code by using java's NIO.
private static void fileCopy(String from, String to) {
FileChannel fromCh = null;
FileChannel toCh = null;
FileInputStream fin = null;
FileOutputStream fout = null;
try {
fin = new FileInputStream(new File(from));
fromCh = fin.getChannel();
fout = new FileOutputStream(new File(to));
toCh = fout.getChannel();
fromCh.transferTo(0, fin.available(), toCh);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fin != null)
try {
fin.close();
} catch (IOException e) {
}
if (fout != null)
try {
fout.close();
} catch (IOException e) {
}
}
}
You can get a file from the original file with the same size.
Check the reference site below:
https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format
I tested it the difference between two file, one is the original another is the copy one. I got an jpeg image from googling.
I modified some code form here in order to analyze the jpeg header file .
Here is the method:
final public static ImageProperties getJpegProperties(File file) throws FileNotFoundException, IOException {
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
// check for "magic" header
byte[] buf = new byte[2];
int count = in.read(buf, 0, 2);
if (count < 2) {
throw new RuntimeException("Not a valid Jpeg file!");
}
if ((buf[0]) != (byte) 0xFF || (buf[1]) != (byte) 0xD8) {
throw new RuntimeException("Not a valid Jpeg file!");
}
int width = 0;
int height = 0;
char[] comment = null;
boolean hasDims = false;
boolean hasComment = false;
int ch = 0;
int totalHeaderLen = 0;
while (ch != 0xDA && !(hasDims && hasComment)) {
/* Find next marker (JPEG markers begin with 0xFF) */
while (ch != 0xFF) {
ch = in.read();
}
/* JPEG markers can be padded with unlimited 0xFF's */
while (ch == 0xFF) {
ch = in.read();
}
/* Now, ch contains the value of the marker. */
int length = 256 * in.read();
length += in.read();
totalHeaderLen += length;
if (length < 2) {
throw new RuntimeException("Not a valid Jpeg file!");
}
/* Now, length contains the length of the marker. */
if (ch >= 0xC0 && ch <= 0xC3) {
in.read();
height = 256 * in.read();
height += in.read();
width = 256 * in.read();
width += in.read();
for (int foo = 0; foo < length - 2 - 5; foo++) {
in.read();
}
hasDims = true;
} else if (ch == 0xFE) {
// that's the comment marker
comment = new char[length - 2];
for (int foo = 0; foo < length - 2; foo++)
comment[foo] = (char) in.read();
hasComment = true;
} else {
// just skip marker
for (int foo = 0; foo < length - 2; foo++) {
in.read();
}
}
}
if(comment == null) comment = "no comment".toCharArray();
return (new ImageProperties(width, height, new String(comment), totalHeaderLen, "jpeg"));
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
}
The main method is :
public static void main(String argv[]) throws IOException {
String imageFile1 = "resource/4.jpg";
String imageFile2 = "resource/4_jpg.jpg";
//copyImage(imageFile1);
ImageProperties origin = getJpegProperties(new File(imageFile1));
ImageProperties copyed = getJpegProperties(new File(imageFile2));
System.out.println("============ Original one ===========");
System.out.println("comments(origin) : " + origin.getComments());
System.out.println("Height(origin) : " + origin.getHeight());
System.out.println("Width(origin) : " + origin.getWidth());
System.out.println("Header Length(origin) : " + origin.getHeaderLen());
//System.out.println("suffix(origin) : " + origin.getSuffix());
System.out.println();
System.out.println("============ Copy one ===========");
System.out.println("comments(copy) : " + copyed.getComments());
System.out.println("Height(copy) : " + copyed.getHeight());
System.out.println("Width(copy) : " + copyed.getWidth());
System.out.println("Header Length(copy) : " + copyed.getHeaderLen());
//System.out.println("suffix(copy) : " + copyed.getSuffix());
}
I copy the original image first using copyImage method here.
static BufferedImage copyImage(BufferedImage source) {
BufferedImage b = new BufferedImage(source.getWidth(), source.getHeight(), source.getType());
Graphics g = b.getGraphics();
g.drawImage(source, 0, 0, null);
g.dispose();
return b;
}
I can see the difference of the two images in the explorer.
I got a different header size when running the program.
The output:
============ Original one ===========
comments(origin) : no comment
Height(origin) : 534
Width(origin) : 800
Header Length(origin) : 21269
============ Copy one ===========
comments(copy) : no comment
Height(copy) : 534
Width(copy) : 800
Header Length(copy) : 603
Header Length is different as you can see the result.
Here is full test code.
package stackoverflow;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class Misc {
public static void main(String argv[]) throws IOException {
String imageFile1 = "resource/4.jpg";
String imageFile2 = "resource/4_jpg.jpg";
String imageFile3 = "resource/4_org.jpg";
fileCopy(imageFile1, imageFile3);
//copyImage(imageFile1);
ImageProperties origin = getJpegProperties(new File(imageFile1));
ImageProperties copyed = getJpegProperties(new File(imageFile2));
System.out.println("============ Original one ===========");
System.out.println("comments(origin) : " + origin.getComments());
System.out.println("Height(origin) : " + origin.getHeight());
System.out.println("Width(origin) : " + origin.getWidth());
System.out.println("Header Length(origin) : " + origin.getHeaderLen());
//System.out.println("suffix(origin) : " + origin.getSuffix());
System.out.println();
System.out.println("============ Copy one ===========");
System.out.println("comments(copy) : " + copyed.getComments());
System.out.println("Height(copy) : " + copyed.getHeight());
System.out.println("Width(copy) : " + copyed.getWidth());
System.out.println("Header Length(copy) : " + copyed.getHeaderLen());
//System.out.println("suffix(copy) : " + copyed.getSuffix());
}
static class ImageProperties {
private final int width;
private final int height;
private final String comments;
private final int headerLen;
private final String suffix;
public ImageProperties(
final int width, final int height, final String comments, final int headerLen,
final String suffix)
{
this.width = width;
this.height = height;
this.comments = comments;
this.suffix = suffix;
this.headerLen = headerLen;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public String getComments() {
return comments;
}
public String getSuffix() {
return suffix;
}
public int getHeaderLen() {
return headerLen;
}
}
final public static ImageProperties getJpegProperties(File file) throws FileNotFoundException, IOException {
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
// check for "magic" header
byte[] buf = new byte[2];
int count = in.read(buf, 0, 2);
if (count < 2) {
throw new RuntimeException("Not a valid Jpeg file!");
}
if ((buf[0]) != (byte) 0xFF || (buf[1]) != (byte) 0xD8) {
throw new RuntimeException("Not a valid Jpeg file!");
}
int width = 0;
int height = 0;
char[] comment = null;
boolean hasDims = false;
boolean hasComment = false;
int ch = 0;
int totalHeaderLen = 0;
while (ch != 0xDA && !(hasDims && hasComment)) {
/* Find next marker (JPEG markers begin with 0xFF) */
while (ch != 0xFF) {
ch = in.read();
}
/* JPEG markers can be padded with unlimited 0xFF's */
while (ch == 0xFF) {
ch = in.read();
}
/* Now, ch contains the value of the marker. */
int length = 256 * in.read();
length += in.read();
totalHeaderLen += length;
if (length < 2) {
throw new RuntimeException("Not a valid Jpeg file!");
}
/* Now, length contains the length of the marker. */
if (ch >= 0xC0 && ch <= 0xC3) {
in.read();
height = 256 * in.read();
height += in.read();
width = 256 * in.read();
width += in.read();
for (int foo = 0; foo < length - 2 - 5; foo++) {
in.read();
}
hasDims = true;
} else if (ch == 0xFE) {
// that's the comment marker
comment = new char[length - 2];
for (int foo = 0; foo < length - 2; foo++)
comment[foo] = (char) in.read();
hasComment = true;
} else {
// just skip marker
for (int foo = 0; foo < length - 2; foo++) {
in.read();
}
}
}
if(comment == null) comment = "no comment".toCharArray();
return (new ImageProperties(width, height, new String(comment), totalHeaderLen, "jpeg"));
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
}
static BufferedImage copyImage(BufferedImage source) {
BufferedImage b = new BufferedImage(source.getWidth(), source.getHeight(), source.getType());
Graphics g = b.getGraphics();
g.drawImage(source, 0, 0, null);
g.dispose();
return b;
}
private static void fileCopy(String from, String to) {
FileChannel fromCh = null;
FileChannel toCh = null;
FileInputStream fin = null;
FileOutputStream fout = null;
try {
fin = new FileInputStream(new File(from));
fromCh = fin.getChannel();
fout = new FileOutputStream(new File(to));
toCh = fout.getChannel();
fromCh.transferTo(0, fin.available(), toCh);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fin != null)
try {
fin.close();
} catch (IOException e) {
}
if (fout != null)
try {
fout.close();
} catch (IOException e) {
}
}
}
}
So, I think the extra information of the jpeg image skipped by the image io library in java.

Unzipping a directory/file in Java

I have the following code:
public static void unzip(final File archive) throws FileNotFoundException, IOException
{
ZipInputStream zipInput = null;
try
{
zipInput = new ZipInputStream(new FileInputStream(archive));
ZipEntry zipEntry = null;
while ((zipEntry = zipInput.getNextEntry()) != null)
{
String ename = zipEntry.getName();
final int pos = ename.lastIndexOf(File.separatorChar);
if (pos >= 0)
{
ename = ename.substring(pos + 1);
}
final FileOutputStream outputFile = new FileOutputStream(archive.getParent() + File.separatorChar + ename);
int data = 0;
try
{
while ((data = zipInput.read()) != -1)
{
outputFile.write(data);
}
}catch (final Exception e)
{
LOGGER.error( e);
}finally
{
outputFile.close();
}
}
}catch (final Exception e)
{
LOGGER.error("Error when zipping file ( "+archive.getPath()+" )", e);
}finally
{
if(zipInput !=null)
{
zipInput.close();
}
}
}
What I would like to know is, what does it mean when I get the value -1 from the following line:
(data = zipInput.read()) != -1
I'm guessing it's the reason why the zip file is not being unzipped properly.
It's an expected value to be returned by an InputStream which has no content left to read.
From InputStream's javadoc :
Returns:
the next byte of data, or -1 if the end of the stream is reached.

File copy from raw to External (secondary) SD card

I know that many question has been answered,
but in my case my code is working properly on Oppo, samsung phone but not work on MI, MOto G, Lenavo phone
Here is my code:
This String return path of secondary SD card:
public static String getExternalStorage() {
File rootFolder = new File("/");
boolean isSdcardRemovable = false;
String path = null;
/* loop: */
for (int i = 0; i < rootFolder.listFiles().length; i++) {
if (rootFolder.listFiles()[i].listFiles() != null
&& !rootFolder.listFiles()[i].toString().contains("system")
&& !rootFolder.listFiles()[i].toString().contains("etc")
&& !rootFolder.listFiles()[i].toString().contains("dev")) {
File dataDir = new File(Environment.getDataDirectory()
.getAbsolutePath());
long dataDirSize = dataDir.getFreeSpace() / (1000 * 1000);
long folderSize = rootFolder.listFiles()[i].getFreeSpace()
/ (1000 * 1000);
if (dataDirSize == folderSize
|| (dataDirSize > folderSize && folderSize > (dataDirSize - 80))) {
System.err
.println("INTERNAL1 " + rootFolder.listFiles()[i]);
System.err.println(dataDirSize);
System.err.println(folderSize);
} else {
File rootSubFolder1 = new File(
rootFolder.listFiles()[i].getAbsolutePath());
if (rootSubFolder1.listFiles() != null) {
for (int j = 0; j < rootSubFolder1.listFiles().length; j++) {
if (rootSubFolder1.listFiles()[j].getTotalSpace() != 0
&& rootSubFolder1.listFiles()[j]
.getFreeSpace() != 0
&& rootSubFolder1.listFiles()[j]
.listFiles() != null) {
Debug.i("fromGetExternalStorage", ""
+ rootSubFolder1.listFiles()[j]);
if (rootSubFolder1.listFiles()[j].toString()
.contains("sdcard")
|| rootSubFolder1.listFiles()[j]
.toString().contains("storage")
|| rootSubFolder1.listFiles()[j]
.toString().contains("mnt")) {
folderSize = rootSubFolder1.listFiles()[j]
.getFreeSpace() / (1000 * 1000);
if (dataDirSize == folderSize
|| (dataDirSize > folderSize && folderSize > (dataDirSize - 80))) {
System.err
.println("INTERNAL2 "
+ rootSubFolder1
.listFiles()[j]);
System.err.println(dataDirSize);
System.err.println(folderSize);
} else {
int pos = rootSubFolder1.listFiles()[j]
.getAbsolutePath().lastIndexOf(
'/');
String str = rootSubFolder1.listFiles()[j]
.getAbsolutePath().substring(
pos + 1);
if (str.matches("(sd|ext|3039|m_external_sd).*")) {
isSdcardRemovable = true;
System.err.println("EXTERNAL "
+ rootSubFolder1
.listFiles()[j]);
System.err.println(dataDirSize);
System.err.println(folderSize);
path = rootSubFolder1.listFiles()[j]
.getAbsolutePath() + "/";
break loop;
}
}
}
}
}
}
}
}
}
if (isSdcardRemovable) {
if (path != null) {
Debug.i("new Path from getExternal Storage", path);
} else {
Debug.i("fail", "External memory not found.");
}
} else {
Debug.i("fail", "External memory not available.");
}
return path;
}`
And This Code that I use path and copy file:
OutputStream OS = new FileOutputStream(path + File.separator + "name.txt");
First Make Directories
File wallpaperDirectory = new File("sdcard/Youpath/");
// have the object build the directory structure, if needed.
if(!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
Code to Copy
final int[] mList= new int[] { R.raw.a, R.raw.b, R.raw.c,R.raw.d,R.raw.e,R.raw.f,
R.raw.g,R.raw.h,R.raw.i,R.raw.j,R.raw.k,R.raw.l,R.raw.m,R.raw.n,R.raw.o,R.raw.p,R.raw.q
,R.raw.r,R.raw.s,R.raw.t,R.raw.u};
for (int i = 0; i < mList.length; i++) {
try {
String path = "sdcard/Youpath/";
File dir = new File(path);
if (dir.mkdirs() || dir.isDirectory()) {
String mName= "YourSetName"+ String.valueOf(i+1) + ".extension";
CopyRAWtoSDCard(mList[i], path + File.separator + mName);
}
} catch (IOException e) {
e.printStackTrace();
}
}
CopyRAWtoSDCard Function
private void CopyRAWtoSDCard(int id, String path) throws IOException {
InputStream in = getResources().openRawResource(id);
FileOutputStream out = new FileOutputStream(path);
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
}

Exception in thread "Thread-9" java.lang.OutOfMemoryError: Java heap space

I have been writing an updater for my game.
It checks a .version file on drop box and compares it to the local .version file.
If there is any link missing from the local version of the file, it downloads the required link one by one.
This is the error that it shows
Exception in thread "Thread-9" java.lang.OutOfMemoryError: Java heap space
at com.fox.listeners.ButtonListener.readFile(ButtonListener.java:209)
at com.fox.listeners.ButtonListener.readFile(ButtonListener.java:204)
at com.fox.listeners.ButtonListener.UpdateStart(ButtonListener.java:132)
at com.fox.listeners.ButtonListener$1.run(ButtonListener.java:58)
It only shows for some computers though and not all of them this is the readFile method
private byte[] readFile(URL u) throws IOException {
return readFile(u, getFileSize(u));
}
private static byte[] readFile(URL u, int size) throws IOException {
byte[] data = new byte[size];
int index = 0, read = 0;
try {
HttpURLConnection conn = null;
conn = (HttpURLConnection) u.openConnection();
conn.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
InputStream is = conn.getInputStream();
progress_a = 0;
progress_b = data.length;
while(index < data.length) {
read = is.read(data, index, size-index);
index += read;
progress_a = index;
}
} catch(Exception e) {
e.printStackTrace();
}
return data;
}
private byte[] readFile(File f) {
byte[] data = null;
try {
data = new byte[(int)f.length()];
#SuppressWarnings("resource")
DataInputStream dis = new DataInputStream(new FileInputStream(f));
dis.readFully(data);
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
This is the main method that is ran
public void UpdateStart() {
System.out.println("Starting Updater..");
if(new File(cache_dir).exists() == false) {
System.out.print("Creating cache dir.. ");
while(new File(cache_dir).mkdir() == false);
System.out.println("Done");
}
try {
version_live = new Version(new URL(version_file_live));
} catch(MalformedURLException e) {
e.printStackTrace();
}
version_local = new Version(new File(version_file_local));
Version updates = version_live.differences(version_local);
System.out.println("Updated");
int i = 1;
try {
byte[] b = null, data = null;
FileOutputStream fos = null;
BufferedWriter bw = null;
for(String s : updates.files) {
if(s.equals(""))
continue;
System.out.println("Reading file "+s);
AppFrame.pbar.setString("Downloading file "+ i + " of "+updates.files.size());
if(progress_b > 0) {
s = s + " " +(progress_a * 1000L / progress_b / 10.0)+"%";
}
b = readFile(new URL(s));
progress_a = 0;
progress_b = b.length;
AppFrame.pbar.setString("Unzipping file "+ i++ +" of "+updates.files.size());
ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(b));
File f = null, parent = null;
ZipEntry entry = null;
int read = 0, entry_read = 0;
long entry_size = 0;
progress_b = 0;
while((entry = zipStream.getNextEntry()) != null)
progress_b += entry.getSize();
zipStream = new ZipInputStream(new ByteArrayInputStream(b));
while((entry = zipStream.getNextEntry()) != null) {
f = new File(cache_dir+entry.getName());
if(entry.isDirectory())
continue;
System.out.println("Making file "+f.toString());
parent = f.getParentFile();
if(parent != null && !parent.exists()) {
System.out.println("Trying to create directory "+parent.getAbsolutePath());
while(parent.mkdirs() == false);
}
entry_read = 0;
entry_size = entry.getSize();
data = new byte[1024];
fos = new FileOutputStream(f);
while(entry_read < entry_size) {
read = zipStream.read(data, 0, (int)Math.min(1024, entry_size-entry_read));
entry_read += read;
progress_a += read;
fos.write(data, 0, read);
}
fos.close();
}
bw = new BufferedWriter(new FileWriter(new File(version_file_local), true));
bw.write(s);
bw.newLine();
bw.close();
}
} catch(Exception e) {
e.printStackTrace();
return;
}
System.out.println(version_live);
System.out.println(version_local);
System.out.println(updates);
CacheUpdated = true;
if(CacheUpdated) {
AppFrame.pbar.setString("All Files are downloaded click Launch to play!");
}
}
I don't get why it is working for some of my players and then some of my other players it does not i have been trying to fix this all day and i am just so stumped at this point but this seems like its the only big issue left for me to fix.
Either increase the memory allocated to your JVM (How can I increase the JVM memory?), or make sure that the file being loaded in memory isn't gigantic (if it is, you'll need to find an alternate solution, or just read chunks of it at a time instead of loading the entire thing in memory).
Do your update in several steps. Here's some pseudo-code with Java 8. It's way shorter than what you wrote because Java has a lot of built-in tools that you re-write much less efficiently.
// Download
Path zipDestination = Paths.get(...);
try (InputStream in = source.openStream()) {
Files.copy(in, zipDestination);
}
// Unzip
try (ZipFile zipFile = new ZipFile(zipDestination.toFile())) {
for (ZipEntry e: Collections.list(zipFile.entries())) {
Path entryDestination = Paths.get(...);
Files.copy(zipFile.getInputStream(e), entryDestination);
}
}
// Done.

Xuggle combine audio with generated audio

I have an mp3 file, and an image. I need to create a video combining them, in java.
I'm trying to do it with xuggle, but there are still no results.
Can anybody give me any suggestions ?
Finally, I found a solution.
I used pieces of code from Xuggle's examples.
I also solved a problem with audio transcoding.
I'll write my code here, because I cannot explain why it works, but it just works.
public String make() throws IOException, InterruptedException {
BufferedImage s1 = genImage();
writer = ToolFactory.makeWriter("temp/" + sermon.getFile().getName() + ".flv");
String filename = sermon.getFile().getAbsolutePath();
IContainer container = IContainer.make();
if (container.open(filename, IContainer.Type.READ, null) < 0) {
throw new IllegalArgumentException("could not open file: " + filename);
}
int numStreams = container.getNumStreams();
int audioStreamId = -1;
IStreamCoder audioCoder = null;
for (int i = 0; i < numStreams; i++) {
IStream stream = container.getStream(i);
IStreamCoder coder = stream.getStreamCoder();
if (coder.getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO) {
audioStreamId = i;
audioCoder = coder;
break;
}
}
if (audioStreamId == -1) {
throw new RuntimeException("could not find audio stream in container: " + filename);
}
if (audioCoder.open() < 0) {
throw new RuntimeException("could not open audio decoder for container: " + filename);
}
writer.addAudioStream(0, 0, audioCoder.getChannels(), audioCoder.getSampleRate());
writer.addVideoStream(1, 1, width, height);
IPacket packet = IPacket.make();
int n = 0;
while (container.readNextPacket(packet) >= 0) {
n++;
if (packet.getStreamIndex() == audioStreamId) {
IAudioSamples samples = IAudioSamples.make(2048, audioCoder.getChannels());
int offset = 0;
while (offset < packet.getSize()) {
try {
int bytesDecoded = audioCoder.decodeAudio(samples, packet, offset);
if (bytesDecoded < 0) {
//throw new RuntimeException("got error decoding audio in: " + filename);
break;
}
offset += bytesDecoded;
if (samples.isComplete()) {
if (n % 1000 == 0) {
writer.flush();
System.out.println(n);
System.gc();
}
writer.encodeAudio(0, samples);
}
} catch (Exception e) {
System.out.println(e);
}
}
} else {
do {
} while (false);
}
}
for (int i = 0; i < container.getDuration() / 1000000; i++) {
writer.encodeVideo(1, s1, i, TimeUnit.SECONDS);
}
writer.close();
if (audioCoder != null) {
audioCoder.close();
audioCoder = null;
}
if (container != null) {
container.close();
container = null;
}
return "temp/" + sermon.getFile().getName() + ".flv";
}
Thanks, good luck.

Categories

Resources