I am working on task to implement external authentication in ejabberd using java.
I searched for the examples on internet and found examples in PHP, Perl, Python but could not find any example in java.
I know the configuration that is required to be made in 'ejabberd.cfg' file.
Any code sample in java will be very helpful.
Try this:
public static void main(String[] args) {
try {
outerloop: while (true) {
byte[] lB = new byte[2];
int startPos = 0;
while (startPos < lB.length) {
int ret = System.in.read(lB, startPos,
(lB.length - startPos));
if (ret < 0) {
break outerloop;
}
startPos += ret;
}
int streamLen = System.in.available();
byte[] rd = new byte[streamLen];
startPos = 0;
while (startPos < streamLen) {
int ret = System.in.read(rd, startPos,
(streamLen - startPos));
if (ret < 0) {
break outerloop;
}
startPos += ret;
}
String inputArgs = new String(rd, "ASCII");
String[] arguments = inputArgs.split(":");
String userName = arguments[1];
String password = arguments[3];
//
// Here do the authentication
//
boolean resultOfAuthentication = // Result of Authentication;
byte[] res = new byte[4];
res[0] = 0;
res[1] = 2;
res[2] = 0;
if (resultOfAuthentication) {
res[3] = 1;
} else {
res[3] = 0;
}
System.out.write(res, 0, res.length);
System.out.flush();
}
} catch (Exception e) {
System.out.println("ERROR");
}
}
Related
I would like to get an Audio wave plot using Chart Area in JavaFX. Unfortunately, I am not clear how to do, what are the values to be extracted from the sound to assign to x-axis and y-axis?
I tried to read other posts, but I found nothing on javafx.
You can help me?
Sample Image:
Below is the code that extract the waveform .
I'm pulling out the right parameters for my scope?
How can I use it to print the graph with JavaFX?
public class SimpleWaveformExtractor implements WaveformExtractor {
private static final int DEFAULT_BUFFER_SIZE = 32768;
#Override
public double[] extract(File inputFile) {
AudioInputStream in = null;
try {
in = AudioSystem.getAudioInputStream(inputFile);
} catch (Exception e) {
System.out.println("Cannot read audio file");
return new double[0];
}
AudioFormat format = in.getFormat();
byte[] audioBytes = readBytes(in);
int[] result = null;
if (format.getSampleSizeInBits() == 16) {
int samplesLength = audioBytes.length / 2;
result = new int[samplesLength];
if (format.isBigEndian()) {
for (int i = 0; i < samplesLength; ++i) {
byte MSB = audioBytes[i * 2];
byte LSB = audioBytes[i * 2 + 1];
result[i] = MSB << 8 | (255 & LSB);
}
} else {
for (int i = 0; i < samplesLength; i += 2) {
byte LSB = audioBytes[i * 2];
byte MSB = audioBytes[i * 2 + 1];
result[i / 2] = MSB << 8 | (255 & LSB);
}
}
} else {
int samplesLength = audioBytes.length;
result = new int[samplesLength];
if (format.getEncoding().toString().startsWith("PCM_SIGN")) {
for (int i = 0; i < samplesLength; ++i) {
result[i] = audioBytes[i];
}
} else {
for (int i = 0; i < samplesLength; ++i) {
result[i] = audioBytes[i] - 128;
}
}
}
return ArraysHelper.normalize(result);
}
private byte[] readBytes(AudioInputStream in) {
byte[] result = new byte[0];
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
try {
int bytesRead = 0;
do {
bytesRead = in.read(buffer);
result = ArrayUtils.addAll(result, buffer);
} while (bytesRead != -1);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
this is the interface:
public interface WaveformExtractor {
double[] extract(File in);
}
This is the code that return the array of double:
private double[] extractWaveform(File file) throws IOException, UnsupportedAudioFileException {
return new WavFileExtractor().extract(file);
}
Alright so I am looking at this piece of code that is supposed to get an array of bytes which represents an image and send it piece by piece to a server. The server needs to be told when the image transmission is done, this ending message is "CLOSE". Everything works fine but unless I uncomment Thread.sleep the end message isn't sent. Also the delay needs to be quite big for some reason, 100 ms for example doesn't work. If anyone could provide an explanation for this behaviour I would be grateful since I don't have a very good understanding of java.
private class NetTask extends AsyncTask<Void, Void, Void>
{
private String ip;
private byte[] to_send;
public NetTask(String ip, byte[] to_send)
{
this.ip = ip;
this.to_send = to_send;
}
#Override
protected Void doInBackground(Void...params)
{
try {
Log.i(dTag, "" + to_send.length);
Socket sck = new Socket(ip, 1234);
DataOutputStream dOut = new DataOutputStream(sck.getOutputStream());
dOut.write(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(to_send.length).array());
Log.d(dTag, "" + to_send.length);
int x = 500;
int len = to_send.length;
for (int i = 0; i < len - x + 1; i += x)
dOut.write(Arrays.copyOfRange(to_send, i, i + x));
if (len % x != 0)
dOut.write(Arrays.copyOfRange(to_send, len - len % x, len));
/*try {
Thread.sleep(1000);
}
catch (Exception ex) {
Log.d(dTag, "thread sleep error");
}*/
dOut.write("CLOSE".getBytes());
dOut.flush();
dOut.close();
sck.close();
}
catch (IOException ex) {
Log.d(dTag, ex.getMessage());
}
return null;
}
}
The server is in c#, here is the code:
while (ok)
{
sck.Listen(1000);
Socket accepted = sck.Accept();
buffer = new byte[accepted.SendBufferSize];
int bytesRead = -1;
bool reading = true;
int im_size = -1;
int index = 0;
byte[] image = null;
while (reading)
{
bytesRead = accepted.Receive(buffer);
if (bytesRead == 5)
Console.WriteLine(bytesRead);
string strData = "YADA";
byte[] formatted = new byte[bytesRead];
if (bytesRead == 5)
{
for (int i = 0; i < bytesRead; i++)
{
formatted[i] = buffer[i];
}
strData = Encoding.ASCII.GetString(formatted);
}
if (strData == "CLOSE")
{
Console.WriteLine("GOT CLOSE MESSAGE");
Image im = Image.FromStream(new MemoryStream(image));
im.Save(#"D:\im1.bmp");
}
else
{
if (im_size == -1)
{
im_size = BitConverter.ToInt32(buffer, 0);
image = new byte[im_size];
Console.WriteLine(im_size);
}
else
{
for (int i = 0; i < bytesRead && index < im_size; i++)
{
image[index++] = buffer[i];
}
}
}
}
accepted.Close();
}
I am trying to upload .JPG file from android to WCF webservice.
To upload the file from Android i tried 2 ways:
1- Retrofit:
#Multipart
#POST("/UploadFile/{fileName}")
void UploadFile(#Path("fileName") String fileName, #Part("image") TypedFile image, Callback<String> callBack);
2- Android Asynchronous Http Client
here there was 2 options for uploading it:
a- Adding InputStream to the RequestParams:
RequestParams params = new RequestParams();
try {
InputStream stream = new FileInputStream(fileImage);
params.put("image", stream, fileImage.getName() );
client.post(Constants.SERVICE_URL + "/UploadFile/" + fileImage.getName()
, params, getResponseHandler());
} catch (Exception e) {
Utils.LogError("ERROR: " + e.getLocalizedMessage());
}
b- Ading File object to the RequestParams:
RequestParams params = new RequestParams();
try {
//InputStream stream = new FileInputStream(fileImage);
params.put("image", fileImage);
client.post(Constants.SERVICE_URL + "/UploadFile/" + fileImage.getName()
, params, getResponseHandler());
} catch (Exception e) {
Utils.LogError("ERROR: " + e.getLocalizedMessage());
}
All those, sent successfully to server, The received file before parsing looks something like this:
--b1b13fd2-4212-45bb-bb5c-fd4dc074fd1b
Content-Disposition: form-data; name="image"; filename="71d9d7fc-cfa8-40b6-b7aa-5c287cf31c72.jpg"
Content-Type: image/jpeg
Content-Length: 2906
Content-Transfer-Encoding: binary
���� JFIF �� C .................very long string of this stuff
Þq�Ã�9�A?� �0pi1�zq�<�#��:��PV���]|�e�K�mv �ǜ.1�q���&��8��u�m�?�ӵ/���0=8�x�:t�8��>�ׁ���1�POM�k����eea1��ǧq�}8�6��q� � �� .;p1K�g�Onz�Q�oås�a�p1�?>3#���z��0=��m$�H ǧ��Ӄ�v?��x��<q��.8܃��� ��2}1�� c���ϧ q�oA�Rt>��t�=�?����2y�q�큊A����:��q�#���_�~�Q�w��Pu��Ƿ�q�#q��{cۦ���}0:b�|�=#��9�BEV���?O��װ�g���z<N� ��� v�=�?������=�<}x�#'�d�8��e����,�\�4wVV���f�pB���㢁�L{��%$�v裶G8x��b�?���� �]�=:�ӕ����
--b1b13fd2-4212-45bb-bb5c-fd4dc074fd1b--
So I used mulipart parser in order to take out the bytes of the file, the write them to file on the server to finish the uploading.
Here is the code of the multipartparser i used:
public class MultipartParser
{
public MultipartParser(string contents)
{
this.Parse(contents);
}
private void Parse(string contents)
{
Encoding encoding = Encoding.UTF8;
this.Success = false;
// Read the stream into a byte array
byte[] data = encoding.GetBytes(contents);
// Copy to a string for header parsing
string content = contents;
// The first line should contain the delimiter
int delimiterEndIndex = content.IndexOf("\r\n");
if (delimiterEndIndex > -1)
{
string delimiter = content.Substring(0, content.IndexOf("\r\n"));
// Look for Content-Type
Regex re = new Regex(#"(?<=Content\-Type:)(.*?)(?=\r\n)");
Match contentTypeMatch = re.Match(content);
// Look for filename
re = new Regex(#"(?<=filename\=\"")(.*?)(?=\"")");
Match filenameMatch = re.Match(content);
#region added
re = new Regex(#"(?<=Content\-Transfer\-Encoding:)(.*?)(?=\r\n\r\n)");
Match contentTransferEncodingMatch = re.Match(content);
#endregion
// Did we find the required values?
if (contentTypeMatch.Success && filenameMatch.Success && contentTransferEncodingMatch.Success)
{
// Set properties
this.ContentType = contentTypeMatch.Value.Trim();
this.Filename = filenameMatch.Value.Trim();
this.ContentEncoding = contentTransferEncodingMatch.Value.Trim();
// Get the start & end indexes of the file contents
//int startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;
int startIndex = contentTransferEncodingMatch.Index + contentTransferEncodingMatch.Length + "\r\n\r\n".Length;
byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter);
string finalDelimeterStr = "\r\n"+delimiter + "--";
byte[] endDilimeterBytes = encoding.GetBytes(finalDelimeterStr);
//byte[] fileBytes = Array.Copy()
//int endIndex = IndexOf(data, endDilimeterBytes, startIndex);
int endIndex = SimpleBoyerMooreSearch(data, endDilimeterBytes);
int contentLength = endIndex - startIndex;
// Extract the file contents from the byte array
byte[] fileData = new byte[contentLength];
Buffer.BlockCopy(data, startIndex, fileData, 0, contentLength);
this.FileContents = fileData;
this.Success = true;
}
}
}
public int SimpleBoyerMooreSearch(byte[] haystack, byte[] needle)
{
int[] lookup = new int[256];
for (int i = 0; i < lookup.Length; i++) { lookup[i] = needle.Length; }
for (int i = 0; i < needle.Length; i++)
{
lookup[needle[i]] = needle.Length - i - 1;
}
int index = needle.Length - 1;
byte lastByte = needle.Last();
while (index < haystack.Length)
{
var checkByte = haystack[index];
if (haystack[index] == lastByte)
{
bool found = true;
for (int j = needle.Length - 2; j >= 0; j--)
{
if (haystack[index - needle.Length + j + 1] != needle[j])
{
found = false;
break;
}
}
if (found)
return index - needle.Length + 1;
else
index++;
}
else
{
index += lookup[checkByte];
}
}
return -1;
}
public static byte[] ToByteArray(Stream stream)
{
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
public bool Success
{
get;
private set;
}
public string ContentType
{
get;
private set;
}
public string ContentEncoding
{
get;
private set;
}
public string Filename
{
get;
private set;
}
public byte[] FileContents
{
get;
private set;
}
}
The parser is taking out the bytes, and parse the received multipart file.
The result file is not showing and it shows error reading file or something.
What i noticed after comparing the files it that the original and received file are different, here is the comparison in Notepad++:
some letters are exists in the original and not exists in the received!
here is the WCF Function declaration and code:
IService.cs:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/UploadFile/{fileName}"
, ResponseFormat = WebMessageFormat.Json)]
string UploadFile(string fileName ,Stream image);
Service.cs:
public string UploadFile(string fileName, Stream image)
{
string dirPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Logs/");
//string path = dirPath+"log.txt";
// Read the stream into a byte array
byte[] data = MultipartParser.ToByteArray(image);
// Copy to a string
string content = Encoding.UTF8.GetString(data);
File.WriteAllText(dirPath + fileName + ".txt", content); // for checking the result file
MultipartParser parser = new MultipartParser(content);
if (parser != null )
{
if (parser.Success)
{
if (parser.FileContents == null)
return "fail: Null Content";
byte[] bitmap = parser.FileContents;
File.WriteAllBytes(dirPath + fileName +"contents",bitmap);
try
{
using (Image outImage = Image.FromStream(new MemoryStream(bitmap)))
{
outImage.Save(fileName, ImageFormat.Jpeg);
}
return "success";
}
catch (Exception e)
{ // I get this exception all the time
return "Fail: e " + e.Message;
}
}
return "fail not success";
}
return "fail";
}
I tried every possible solution came to my mind, still could not get whats wrong!!! is the problem in the encoding while sending or the parser!??
Please what can be the problem!? i am struggling with this for 3 days!
Thank you ALL :)
The were 2 problems:
The parser
Decoding the bytes to string was not good idea.
I modified the parser to this one and it will take care of the rest:
public class MultipartParser
{
public MultipartParser(Stream stream)
{
this.Parse(stream);
}
private void Parse(Stream stream)
{
this.Success = false;
if(!stream.CanRead)
return;
// Read the stream into a byte array
byte[] data = MultipartParser.ToByteArray(stream);
if (data.Length < 1)
return;
// finding the delimiter (the string in the beginning and end of the file
int delimeterIndex = MultipartParser.SimpleBoyerMooreSearch(data, Encoding.UTF8.GetBytes("\r\n")); // here we got delimeter index
if (delimeterIndex == -1) return;
byte[] delimeterBytes = new byte[delimeterIndex];
Array.Copy(data, delimeterBytes, delimeterIndex);
// removing the very first couple of lines, till we get the beginning of the JPG file
byte[] newLineBytes = Encoding.UTF8.GetBytes("\r\n\r\n");
int startIndex = 0;
startIndex = MultipartParser.SimpleBoyerMooreSearch(data, newLineBytes);
if (startIndex == -1)
return;
int startIndexWith2Lines = startIndex + 4; // 4 is the bytes of "\r\n\r\n"
int newLength = data.Length - startIndexWith2Lines;
byte[] newByteArray = new byte[newLength];
Array.Copy(data, startIndex + 4, newByteArray, 0, newLength - 1);
// check for the end of the stream, is ther same delimeter
int isThereDelimeterInTheEnd = MultipartParser.SimpleBoyerMooreSearch(newByteArray, delimeterBytes);
if (isThereDelimeterInTheEnd == -1) return; // the file corrupted so
int endIndex = isThereDelimeterInTheEnd - delimeterBytes.Length;
byte[] lastArray = new byte[endIndex];
Array.Copy(newByteArray, 0, lastArray, 0, endIndex);
this.FileContents = lastArray;
this.Success = true;
}
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
public static int SimpleBoyerMooreSearch(byte[] haystack, byte[] needle)
{
int[] lookup = new int[256];
for (int i = 0; i < lookup.Length; i++) { lookup[i] = needle.Length; }
for (int i = 0; i < needle.Length; i++)
{
lookup[needle[i]] = needle.Length - i - 1;
}
int index = needle.Length - 1;
byte lastByte = needle.Last();
while (index < haystack.Length)
{
var checkByte = haystack[index];
if (haystack[index] == lastByte)
{
bool found = true;
for (int j = needle.Length - 2; j >= 0; j--)
{
if (haystack[index - needle.Length + j + 1] != needle[j])
{
found = false;
break;
}
}
if (found)
return index - needle.Length + 1;
else
index++;
}
else
{
index += lookup[checkByte];
}
}
return -1;
}
private int IndexOf(byte[] searchWithin, byte[] serachFor, int startIndex)
{
int index = 0;
int startPos = Array.IndexOf(searchWithin, serachFor[0], startIndex);
if (startPos != -1)
{
while ((startPos + index) < searchWithin.Length)
{
if (searchWithin[startPos + index] == serachFor[index])
{
index++;
if (index == serachFor.Length)
{
return startPos;
}
}
else
{
startPos = Array.IndexOf<byte>(searchWithin, serachFor[0], startPos + index);
if (startPos == -1)
{
return -1;
}
index = 0;
}
}
}
return -1;
}
public static byte[] ToByteArray(Stream stream)
{
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
public bool Success
{
get;
private set;
}
public byte[] FileContents
{
get;
private set;
}
}
So you can use this parser for this kind of multipart files encoding:
--b1b13fd2-4212-45bb-bb5c-fd4dc074fd1b
Content-Disposition: form-data; name="image"; filename="71d9d7fc-cfa8-40b6-b7aa-5c287cf31c72.jpg"
Content-Type: image/jpeg
Content-Length: 2906
Content-Transfer-Encoding: binary
���� JFIF �� C .................very long string of this stuff
Þq�Ã�9�A?� �0pi1�zq�<�#��:��PV���]|�e�K�mv �ǜ.1�q���&��8��u�m�?�ӵ/��Ƿ�q�#q��{cۦ���}0:b�|�=#��9�BEV���?O��װ�g���z<N� ��� v�=�?������=�<}x�#'�d�8��e����,�\�4wVV���f�pB���㢁�L{��%$�v裶G8x��b�?���� �]�=:�ӕ����
--b1b13fd2-4212-45bb-bb5c-fd4dc074fd1b--
Hope it helps somebody else.
You could try to encode the jpeg to base64 before sending it. As far as I know, this is a proper solution. Decoding it on the server, should be no problem. (Sry, I wanted to write a comment - but I'm not allowed to it)
I trying to write a code to stream from shoutcast server
and I use the below code and give me javax.sound.sampled.UnsupportedAudioFileException
how I can solve the exception
public static void streamSampledAudio(URL url)
throws IOException, UnsupportedAudioFileException,
LineUnavailableException
{
AudioInputStream ain = null; // We read audio data from here
SourceDataLine line = null; // And write it here.
try {
InputStream is = url.openStream();
BufferedInputStream bis = new BufferedInputStream( is );
ain=AudioSystem.getAudioInputStream(bis);
AudioFormat format = ain.getFormat( );
DataLine.Info info=new DataLine.Info(SourceDataLine.class,format);
if (!AudioSystem.isLineSupported(info)) {
AudioFormat pcm =
new AudioFormat(format.getSampleRate( ), 16,
format.getChannels( ), true, false);
ain = AudioSystem.getAudioInputStream(pcm, ain);
format = ain.getFormat( );
info = new DataLine.Info(SourceDataLine.class, format);
}
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(format);
int framesize = format.getFrameSize( );
byte[ ] buffer = new byte[4 * 1024 * framesize]; // the buffer
int numbytes = 0; // how many bytes
boolean started = false;
for(;;) { // We'll exit the loop when we reach the end of stream
int bytesread=ain.read(buffer,numbytes,buffer.length-numbytes);
if (bytesread == -1) break;
numbytes += bytesread;
if (!started) {
line.start( );
started = true;
}
int bytestowrite = (numbytes/framesize)*framesize;
line.write(buffer, 0, bytestowrite);
int remaining = numbytes - bytestowrite;
if (remaining > 0)
System.arraycopy(buffer,bytestowrite,buffer,0,remaining);
numbytes = remaining;
}
line.drain( );
}
finally { // Always relinquish the resources we use
if (line != null) line.close( );
if (ain != null) ain.close( );
}
}
and give me an exception
Exception in thread "main" javax.sound.sampled.UnsupportedAudioFileException: could not get audio
input stream from input stream
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at test.PlaySoundStream.streamSampledAudio(PlaySoundStream.java:40)
at test.PlaySoundStream.main(PlaySoundStream.java:21)
can help me to solve the exception
or tell me about away can stream by it from shoutcast
I try this code to download MP3 from shoutcast and then you can play sound
public class DownloadMP3 {
private boolean halt = false;
public static final String DEFAULT_HOST = "127.0.0.1";
protected String host = "url";
public static final int DEFAULT_PORT = 80;
protected int port = 8568;
public static final int DEFAULT_TOTAL_SIZE = 0;
protected long totalSize = 0L;
public static final int DEFAULT_CHUNK_SIZE = 0;
long chunkSize = 0L;
public static final String DEFAULT_OUTPUT_DIRECTORY = ".";
File outputDirectory = new File("D:\\");
public static void main(String[ ] args) throws Exception {
DownloadMP3 d = new DownloadMP3();
d.run();
}
public void run()
{
Socket localSocket = null;
PrintWriter localPrintWriter = null;
BufferedInputStream localBufferedInputStream = null;
FileOutputStream localFileOutputStream = null;
try
{
writeMessage("Opening connection to " + this.host + ":" + this.port);
localSocket = new Socket(this.host, this.port);
localPrintWriter = new PrintWriter(localSocket.getOutputStream(), true);
localBufferedInputStream = new BufferedInputStream(localSocket.getInputStream());
localPrintWriter.print("GET / HTTP/1.0\r\n\r\n");
localPrintWriter.flush();
byte[] arrayOfByte = new byte[1024];
long l1 = 0L;
long l2 = 0L;
int i = 1;
File localFile = null;
writeMessage("Host contacted, waiting for response...");
try
{
int k = 0;
int m;
writeMessage("Recieving Data....");
int j;
while ((j = localBufferedInputStream.read(arrayOfByte)) != -1) {
if ((localFileOutputStream == null) || ((this.chunkSize > 0L) && (l2 + j >= this.chunkSize))) {
m = findSync(arrayOfByte, 0, j);
if (m == -1) {
m = j;
}
if (localFileOutputStream != null)
{
localFileOutputStream.write(arrayOfByte, 0, m);
}
if (localFileOutputStream != null) {
localFileOutputStream.close();
}
while ((localFile = new File(this.outputDirectory, this.host + '-' + this.port + '-' + formatFileNum(i++) + ".mp3")).exists());
writeMessage("Saving to file: " + localFile);
localFileOutputStream = new FileOutputStream(localFile);
l2 = 0L;
localFileOutputStream.write(arrayOfByte, m, j - m);
l2 += j - m;
} else {
localFileOutputStream.write(arrayOfByte, 0, j);
l2 += j;
}
if ((this.totalSize > 0L) && (l1 >= this.totalSize)) {
writeMessage("Capture completed successfully.");
if (this.halt) {
writeMessage("Capture interruted.");
}
}
writeErrorMessage("Connection closed by host.");
return;
} catch (IOException localIOException2) {
if (this.halt)
writeMessage("Capture interruted.");
else {
writeErrorMessage(localIOException2.getMessage());
}
} finally {
if (localFileOutputStream != null)
localFileOutputStream.close();
}
}
catch (UnknownHostException localUnknownHostException) {
writeErrorMessage("Unknown host: " + this.host);
return;
} catch (IOException localIOException1) {
writeErrorMessage("Could not connect to " + this.host + " on port " + this.port);
}
finally {
if (localPrintWriter != null) {
localPrintWriter.close();
}
if (localBufferedInputStream != null)
try {
localBufferedInputStream.close();
}
catch (IOException localIOException3) {
}
if (localSocket != null)
try {
localSocket.close();
}
catch (IOException localIOException4)
{
}
}
}
private static int findSync(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
{
for (int i = paramInt1; i < paramInt2 - 1; i++) {
if (((paramArrayOfByte[i] & 0xFF) == 255) && ((paramArrayOfByte[(i + 1)] & 0xE0) == 224)) {
return i;
}
}
return -1;
}
private static String formatFileNum(int paramInt)
{
if (paramInt < 10)
return "00" + paramInt;
if (paramInt < 100) {
return "0" + paramInt;
}
return "" + paramInt;
}
protected void writeMessage(String paramString)
{
System.out.println(paramString);
}
protected void writeErrorMessage(String paramString)
{
System.err.println(paramString);
}
}
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.