Capturing with vlcj only gives a corrupt video file - vlc

I am using vlcj to capture the screen in my Java program. Therefore I use the following code:
public static void main(final String[] args) {
NativeLibrary.addSearchPath("vlc", "/Applications/VLC.app/Contents/MacOS/lib/");
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new CaptureTest().start("screen://");
}
});
}
public CaptureTest() {
factory = new MediaPlayerFactory();
mediaPlayer = (HeadlessMediaPlayer) factory.newMediaPlayer();
}
private void start(String mrl) {
File dir = new File(System.getProperty("user.home"), "Videos");
dir.mkdirs();
DateFormat df = new SimpleDateFormat("yyyyMMdd-HHmmss");
String fileName = dir.getAbsolutePath() + "/Capture-" + df.format(new Date()) + ".mp4";
String[] options = {
":sout=#transcode{vcodec=h264,acodec=mp4a}:std{mux=mp4,access=file,dst=" + fileName + "}", ":input-slave=screen://"
};
mediaPlayer.playMedia(mrl, options);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mediaPlayer.stop();
mediaPlayer.release();
}
The problem is that the video output file is only 4KB and you can't play it. Can anyone help me? I am on Mac OS 10.6.8 and I use VLC 1.1.12 and vlcj 1.1.5

Here is the interesting part of your code...
mediaPlayer.playMedia(mrl, options);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mediaPlayer.stop();
mediaPlayer.release();
Why did you play the media, slept for 5 seconds and stopped immediately after that? Maybe, this is why you get a very small file size during the screen recording. From what I notice, the transcode is not so fast enough, so the file is not increasing in size immediately (maybe due to buffering takes place during transcoding part, I guess...)
The best is to create a button each for the play/record action and for the stop action.

You might check your sout chain. I also had problem with video file generation. The working sout chain for me is :
:sout=#transcode{vcodec=mp2v, vb=4096,scale=1, acodec=mpga, ab=128, channels=2, samplerate=44100}
:duplicate{dst=file{dst="+ fileName+"}, dst=display, select=noaudio}

Related

Gluon iOS audio Player

I've been following various answers to various questions on the subject and I've come to a result and some code which looks like it works. I'm getting stuck with the NSURL part of it. I've got 2 mp3 tracks in the assets folder of my iOS gluon project. I've made the IOSAudioService Class to handle the playback. and I'm passing an argument from the play button in the view to the Play() method. Everything other than the actual file is registering as working. I'm getting an NSError, which from looking at the code is a nil value, so either the argument isn't passing correctly or it can't find the file. Code below.
public AVAudioPlayer backgroundMusic;
private double currentPosition;
NSURL songURL = null;
#Override
public void Play(String filename){
songURL = new NSURL(filename);
try {
if (backgroundMusic != null) {
Resume();
}
else {
//Start the audio at the beginning.
currentPosition = 0;
backgroundMusic = new AVAudioPlayer(songURL);
//create the mendia player and assign it to the audio
backgroundMusic.prepareToPlay();
backgroundMusic.play();}
//catch the audio error
} catch(NSErrorException e) {
System.out.println("error: " + e);
}
}
#Override
public void Stop() {
backgroundMusic.stop();
backgroundMusic = null;
}
#Override
public void Pause() {
currentPosition = backgroundMusic.getCurrentTime();
backgroundMusic.pause();
}
#Override
public void Resume() {
backgroundMusic.setCurrentTime(currentPosition);
backgroundMusic.play();
}
try {
services = (AudioService) Class.forName("com.gluonhq.charm.down.plugins.ios.IOSAudioService").newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
System.out.println("Error " + ex);
}
I'm getting the error at the catch block for NSExceptionError e.
if (services != null) {
final HBox hBox = new HBox(10,
MaterialDesignIcon.PLAY_ARROW.button(e -> services.Play("/audio.mp3")),
MaterialDesignIcon.PAUSE.button(e -> {
if (!pause) {
services.Pause();
pause = true;
} else {
services.Resume();
pause = false;
}
}),
MaterialDesignIcon.STOP.button(e -> services.Stop()));
//set the HBox alignment
hBox.setAlignment(Pos.CENTER);
hBox.getStyleClass().add("hbox");
//create and set up a vbox to include the image, audio controls and the text then set the alignment
final VBox vBox = new VBox(5, Image(), hBox, text1);
vBox.setAlignment(Pos.CENTER);
setCenter(new StackPane(vBox));
} else {
//start an error if service is null
setCenter(new StackPane(new Label("Only for Android")));
}
Services.get(LifecycleService.class).ifPresent(s -> s.addListener(LifecycleEvent.PAUSE, () -> services.Stop()));
}
I've also follow the advice on creating the service factory class and the interface from Audio performance with Javafx for Android (MediaPlayer and NativeAudioService) taking out the add audio element and I'm intending to do this on a view by view basis if possible.
Problem solved after must fiddling and looking in the Javadocs.Solved by adding/replacing some code with the below.
songURL = new NSURL("file:///" + NSBundle.getMainBundle().findResourcePath(filename, "mp3"));
try {
songURL.checkResourceIsReachable();}
catch(NSErrorException d) {
System.out.println("Song not found!" + d);
}

How to compress the files in Blackberry?

In my application I used html template and images for browser field and saved in the sdcard . Now I want to compress that html,image files and send to the PHP server. How can I compress that files and send to server? Provide me some samples that may help lot.
i tried this way... my code is
EDIT:
private void zipthefile() {
String out_path = "file:///SDCard/" + "newtemplate.zip";
String in_path = "file:///SDCard/" + "newtemplate.html";
InputStream inputStream = null;
GZIPOutputStream os = null;
try {
FileConnection fileConnection = (FileConnection) Connector
.open(in_path);//read the file from path
if (fileConnection.exists()) {
inputStream = fileConnection.openInputStream();
}
byte[] buffer = new byte[1024];
FileConnection path = (FileConnection) Connector
.open(out_path,
Connector.READ_WRITE);//create the out put file path
if (!path.exists()) {
path.create();
}
os = new GZIPOutputStream(path.openOutputStream());// for create the gzip file
int c;
while ((c = inputStream.read()) != -1) {
os.write(c);
}
} catch (Exception e) {
Dialog.alert("" + e.toString());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
Dialog.alert("" + e.toString());
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
Dialog.alert("" + e.toString());
}
}
}
}
this code working fine for single file but i want to compress all the file(more the one file)in the folder .
In case you are not familiar with them, I can tell you that in Java the stream classes follow the Decorator Pattern. These are meant to be piped to other streams to perform additional tasks. For instance, a FileOutputStream allows you to write bytes to a file, if you decorate it with a BufferedOutputStream then you get also buffering (big chunks of data are stored in RAM before being finally written to disc). Or if you decorate it with a GZIPOutputStream then you get also compression.
Example:
//To read compressed file:
InputStream is = new GZIPInputStream(new FileInputStream("full_compressed_file_path_here"));
//To write to a compressed file:
OutputStream os = new GZIPOutputStream(new FileOutputStream("full_compressed_file_path_here"));
This is a good tutorial covering basic I/O . Despite being written for JavaSE, you'll find it useful since most things work the same in BlackBerry.
In the API you have these classes available:
GZIPInputStream
GZIPOutputStream
ZLibInputStream
ZLibOutputStream
If you need to convert between streams and byte array use IOUtilities class or ByteArrayOutputStream and ByteArrayInputStream.

How to stop progressbar in blackberry

In BlackBerry, my application is working perfectly fine. But one Requirement is when I load data from server, a progress bar is showing. If it takes so much time to load data from server, then I want to stop the progress bar. In BlackBerry, on back key pressed, it is not working. Please help me.
public class WaitScreen extends PopupScreen
{
public WaitScreen(String msg) {
super(new HorizontalFieldManager());
add(new LabelField(msg));
AnimatedGIFField testanimated = new AnimatedGIFField(
(GIFEncodedImage) (GIFEncodedImage.getEncodedImageResource("ajax_loader.gif")),
AnimatedGIFField.FIELD_HCENTER | AnimatedGIFField.FIELD_VCENTER);
add(testanimated);
}
}
public long timeout=0;
t.schedule(new TimerTask() {
public void run()
{
// TODO Auto-generated method stub
timeout+=1;
System.out.println("Timeout value:"+timeout);
if(timeout>=28)
{
//timeout every 1 munite
System.out.println("Timeout value:"+timeout);
System.out.println("closing connection");
try
{
parent.notifyDestroyed();
}
catch (Exception ex)
{
System.out.println("Exception is:"+ex);
}
this.cancel();
}
}
}, 0, 1000);
// Thread.sleep(30000);
httpconn_post = (HttpConnection) Connector.open(url);
httpconn_post.setRequestMethod(HttpConnection.POST);
httpconn_post.setRequestProperty("Accept_Language","en-US");
httpconn_post.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = httpconn_post.openOutputStream();
out.write(param.getBytes());
out.flush();
System.out.println("Status Line Code: " + httpconn_post.getResponseCode());
System.out.println("Status Line Message: " + httpconn_post.getResponseMessage());
if ( httpconn_post.getResponseCode()== HttpConnection.HTTP_OK )
{
is=httpconn_post.openDataInputStream();
// cancelling timer
t.cancel();
.....
.....
}
I had done this using this code..I had done it successfully..

Audio Recording Not Getting setRecordLocation()

I am trying to save audio at a specified device location on Button Click (which invokes run() method). This is my code.
public Audio() {
}
public void run()
{
try{
try{
_player = Manager.createPlayer("capture://audio?encoding=audio/amr");
}
catch(MediaException e)
{
Dialog.alert(e.toString());
}
_player.realize();
_rControl =(RecordControl)_player.getControl("RecordControl");
try{
**//Point 1//**_rControl.setRecordLocation("file:///Device Memory/samples/ringtones/recordTest1.amr");
}
catch(MediaException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
_rControl.startRecord();
_player.start();
System.out.println("<<--Successful-->>>");
}
catch(Exception e){e.printStackTrace();}
}
public void stop()
{
try{
if(_rControl != null)
{
_rControl.stopRecord();
try{
_rControl.commit();
}catch(Exception e){e.printStackTrace();}
_rControl = null;
}
if(_player != null)
{
_player.close();
_player=null;
}
}catch(Exception e){e.printStackTrace();}
}
In run() method, i am getting IOException at Point 1 where i am trying to set location for audio file. But when I tried this:
{
_rControl.setRecordLocation("file:///system/samples/ringtones/recordTest1.amr");
}
i found it working with 9550 simulator but not with 8900 simulator. So what location should i set to make this working with 8900 simulator and also 8900 blackberry device?
You should use:
javax.microedition.io.file.FileSystemRegistry.listRoots()
to get available root file systems on the device running the code.

problems in silverlight 4 when using Action callbacks to check for successful file upload

So the async requirement for silverlight ends up in some really convoluted code!!
Im uploading a file just exactly like this answer suggests.
The difference is Im posting the file to an MVC action method. Everything works file except, like I commented on the bottom of that answer, I don't get any callback for when the file DOES NOT successfully upload.
So I created another action method in my mvc app (Services/CheckForFile/{id}) and it returns a string depending on whether the file is found.
Now, how and when do I call this mvc action method is the problem:
void DoUpload() { //Gets call on BtnUpload.Click
//opn is an OpenFileDialog
up.UploadFile(_filename, opn.File.OpenRead(),
e =>
{
//do some ui stuff here.
BeginCheck();// calling this causes PROBLEMS!
});
}
private void BeginCheck()
{
Uploader up = new Uploader();
up.CheckForFile(_filename, success =>
{
if (!success)
{
MessageBox.Show("There was problem uploading the file. Please try again", "Error", MessageBoxButton.OK);
}
});
}
Here is the problem:
When the BeginCheck() function runs, the file, for some reason, NEVER uploads! If I comment it out it does!? It seems like The BeginCheck() runs during the upload or something? Shouldn't it run after!?
How/where would I call BeginCheck() after the upload, to ensure the file has been uploaded?
Here is how I defined the Uploader class:
public class Uploader
{
public void UploadFile(string fileName, Stream data, Action<Exception> callback)
{
UriBuilder ub = new UriBuilder(_mvcurl+"Services/UploadFile/" + fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
try
{
PushData(data, e.Result);
e.Result.Close();
data.Close(); //this does not block.
callback(null);//this ALWAYS hits!
}
catch (Exception err)
{
if (callback != null)
{
callback(err);
}
}
};
c.OpenWriteAsync(ub.Uri);
}
public void CheckForFile(string filename, Action<bool> callback)
{
UriBuilder ub = new UriBuilder(_mvcurl+"Services/CheckForFile/" + fileName);
WebClient c = new WebClient();
c.OpenReadCompleted += (sender, e) =>
{
using (StreamReader sw = new StreamReader(e.Result))
{
if (sw.ReadToEnd().Equals("Found", StringComparison.InvariantCultureIgnoreCase))
{
callback(true);
}
else
{
callback(false);
}
}
};
c.OpenReadAsync(ub.Uri);
}
private void PushData(Stream input, Stream output)
{//4KB is not a limitation. We only copy 4Kb at a time from in to out stream
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}
I'm embarrased to say that the original answer of mine to which you refer isn't entirely accurate. It seems to work for what the OP wanted but in fact the code doesn't block at the point that I thought it did. In reality what you are actually looking for is the WriteStreamClosed event, its here that you can discover any failure of the request.
Here is an ammended version that works the way you are expecting:-
public void UploadFile(string fileName, Stream data, Action<Exception> callback)
{
UriBuilder ub = new UriBuilder(_mvcurl+"Services/UploadFile/" + fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
try
{
PushData(data, e.Result);
e.Result.Close();
data.Close(); //this does not block.
}
catch (Exception err)
{
if (callback != null)
callback(err);
}
};
c.WriteStreamClosed += (sender, e) =>
{
if (callback != null)
callback(e.Error);
}
c.OpenWriteAsync(ub.Uri);
}
Now your BeginCheck will only run after the server has responded to the file upload.

Resources