How to target a file (a path to it) in Java/JavaFX - file

It might be a simple one, but i can't seem to get it to work. I am making a video player in JavaFX but I don't know how to target the file that is going to be played (I don't know the correct syntax). Thank you in advance for your help. Here's a sample of code that i'm trying to run>
Media media = new Media("trailers/trailer.mp4");
MediaPlayer player = new MediaPlayer(media);
MediaView view = new MediaView(player);
btw, the file is in the project folder, then trailers/trailer.mp4. Oh, and I'm running Windows.

1 Use this if media source file in same project package.
Media media = new Media("trailer.mp4");
2 Use this if media source file in same project sub package [Packages with name "trailers" in project main package]
Media media = new Media("trailers/trailer.mp4");
3 Use this if media source file is other location [Using full path].
Media media = new Media("file:///e:/trailers/trailer.mp4");
OR
Media media = new Media("file:///E:/trailers/trailer.mp4");
Note: should use 3 slash i.e. "file:///" to avoid error "MediaException: MEDIA_INACCESSIBLE : e/E"

Put your file into the sources folder and load it as a resource:
Media media = new Media(getClass().getResource("trailer.mp4"));
or use the full path
Media media = new Media("file://c:/trailers/trailer.mp4"));
Also, note that JavaFX 2.0 supports only FLV codec. For mp4 (with H.264 codec) you need to use JavaFX 2.1 or later.

If you want to load media from your project package:
File file=new File("trailer.mp4");
Media media=new Media(file.toURI().toString())

Related

Playing Background Music From Bundled File in Codenameone

I'm trying to have a background sound play in codenameone from an mp3 file that's packaged with the app (beep-07.mp3 is just in the src folder).
I can make it work using MediaManager.createMedia, with code borrowed from this post: How to bundle sounds with Codename One?
But the MediaManager.createBackgroundMedia function only takes in a uri, so I try using MediaManager.createBackgroundMedia("file://beep-07.mp3"); but no sound plays.
Am I doing something wrong in the file string?
The src directory doesn't exist on the device. The files that are there are packaged as resources into the equivalent of a jar. So you need to extract them if you want a URL. Notice this might work with "jar://beep-07.mp3" but I'm not sure.
A more correct approach would be to extract it from the jar on first use then use this URL (the code below assumes static import of the CN class):
String fileName = getAppHomePath() + "beep-07.mp3";
if(!existsInFileSystem(fileName)) {
try(InputStream i = getResourceAsStream("/beep-07.mp3");
OutputStream o = openFileOutputStream(fileName)) {
copy(i, o);
}
}
Media m = MediaManager.createBackgroundMedia(fileName);
FYI since your app is running you don't need background media only foreground media.

Stream YouTube video from extracted url

I am trying to find solution to play YouTube video from http stream. Not as embedded player or via website. The reason of that as I need to play some clips locally in app that prevented to be embedded.
So the first task to obtain http stream is easy to solve, e.g. using YouTubeExtractor. For example from this youtube url
https://www.youtube.com/watch?v=31crA53Dgu0
YouTubeExtractor extracts such url for downloading video. As you can see there is no piece of path to concrete .mp4 or .mov file. There is also binding to IP, so the url won't work on your side.
https://r3---sn-puu8-3c2e.googlevideo.com:443/videoplayback?sparams=dur,gcr,id,initcwndbps,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pl,ratebypass,requiressl,source,upn,expire&source=youtube&initcwndbps=3147500&pl=19&upn=oYYkSNBwoc8&fexp=9412913,9416126,9416891,9422596,9428398,9429016,9431012,9431364,9431901,9432206,9432825,9433096,9433424,9433623,9433946,9434085,9435504,9435703,9435937&id=o-AGanAaajMgOmp4VrXIwo9jewJnqlsvZecDxCcRpSN3lS&expire=1462821352&gcr=ua&ip=12.34.56.149&lmt=1458705532562546&ms=au&mt=1462799507&mv=m&dur=217.849&sver=3&itag=22&key=yt6&mn=sn-puu8-3c2e&mm=31&ipbits=0&mime=video/mp4&ratebypass=yes&requiressl=yes&signature=A142619EBA90D00CC46FF05B9CF1E3469B0EF196.072B532670A4D833582F94CF9C46F1F7D298F230&fallback_host=tc.v1.cache5.googlevideo.com
private string ExtractVideoUrl(string youtubeUrl)
{
IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(youtubeUrl, false);
var video = videoInfos.First();
if (video.RequiresDecryption)
{
DownloadUrlResolver.DecryptDownloadUrl(video);
}
return video.DownloadUrl; // videoInfos.First().DownloadUrl;
}
Then to download video this lib uses the code below. The interesting moment is in reading stream and writing to file the contents of youtube video.
var request = (HttpWebRequest)WebRequest.Create(this.Video.DownloadUrl);
if (this.BytesToDownload.HasValue)
{
request.AddRange(0, this.BytesToDownload.Value - 1);
}
// the following code is alternative, you may implement the function after your needs
using (WebResponse response = request.GetResponse())
{
using (Stream source = response.GetResponseStream())
{
**// HOW to Play source stream???**
using (FileStream target = File.Open(this.SavePath, FileMode.Create, FileAccess.Write))
{
var buffer = new byte[1024];
bool cancel = false;
int bytes;
int copiedBytes = 0;
while (!cancel && (bytes = source.Read(buffer, 0, buffer.Length)) > 0)
{
target.Write(buffer, 0, bytes);
....
So the general question is how to play video from that open stream? For example Chrome, Firefox and KMPlayer are doing this easily. The browsers generate a simple page with video tag, so it will be trivial to manage the player through JS. But...internal WebBrowser control can't, it suggests to download file. I tried CEFSharp (Chrome Embeded Framework) and no luck there. Maybe anybody know good video player WPF library which can streaming video? I also tried VLC.wpf and Shockwave Flash, but still unhappy with this extracted url. A lot of searching but results insufficient for now.
After 2 days researching I found the solution of how to play youtube video url directly from WPF application.
Some notes before:
WebBrowser component for WPF and the same for WinForms does not support HTML5. So no way to play video using <video> tag there
Chrome Embeded Framework (CEF)and its CEFSharp wrapper does not support <audio> and <video> tags by default. As I found on SO it is needed to recompile CEF to support audio and it seems video too. --enable-multimedia-streams option didn't work on my side at all to play video
WPF MediaElement component does not support playing video from streams. However there are workaroung exists, they are unsuitable to play youtube url's.
No .NET media player found which could play video from Stream object returned by HttpWebRequest
So the solution is in using GeckoFx webbrowser which is also available via nuget. As it is WinForms based component it is needed to use WinFormsHosting to use it in WPF. Final solution is:
<xmlns:gecko="clr-namespace:Gecko;assembly=Geckofx-Winforms">
....
<WindowsFormsHost Width="400" Height="300" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >
<gecko:GeckoWebBrowser x:Name="_geckoBrowser"/>
</WindowsFormsHost>
And simple code to use:
public void PlayVideo(string videoId)
{
var url = string.Format("https://www.youtube.com/watch?v={0}", videoId);
var videoUrl = ExtractVideoUrl(url);
_geckoBrowser.Navigate(videoUrl);
}
GeckoFx is depeneded on XulRunner runtime sdk. It is installed with nuget package though. One cons in this solution is the size of all app dependencies increased for over +70mb.

Why won't any other video file format work except .mov?

I have an app on the app store which plays a selection of videos. Currently all of the videos are in the .mov file format but this makes the size of the app rather large so i'm trying to use a different file format to reduce the overall size of the app.
I am trying to use the mp4 format as this is reducing the size of each video by more than a half but when I do, the app crashes when I try to play the video with the following error message:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSURL initFileURLWithPath:]: nil string parameter
I have used the following code for each video in my implementation file and changed the file name and type to match the new video so I don't understand why there should be a problem with the file path.
- (IBAction)playDaresWins:(id)sender {
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"DaresWins" ofType:#"mov"]];
_moviePlayer =
[[MPMoviePlayerController alloc]
initWithContentURL:url];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:_moviePlayer];
_moviePlayer.controlStyle = MPMovieControlStyleNone;
_moviePlayer.shouldAutoplay = YES;
[self.view addSubview:_moviePlayer.view];
[_moviePlayer setFullscreen:YES animated:NO];
}
Am I missing something?
.mov isn't a video format or codec, it's a container. The developer documentation provides a list of supported video codecs, bit rates, and resolution (link here - I won't post them here as they can change from OS version to OS version).
However, I don't think that's the problem, because it looks as if you're getting an exception when you're creating the NSURL, not when you're playing the video. That suggests that the path you're providing for your video doesn't exist. Are you sure you have a) the right filename, b) the right extension (perhaps it's MP4 instead of MOV), or c) have added the movie file into your project correctly?

How to create new File txt by using Adobe Air

I want to ask how to create new file with adobe air so i can write it.....
And how to put it in our current project?
I have seen so many resource, but they used existed file that created manually and only update it content...
Thanks Alot
everything is explained (with sample code) in the documentation:
flash.filesystem.FileStream
flash.filesystem.File
Reading and writing files (Adobe AIR 1.0 and later)
private var fileReferenceSave:FileReference= new FileReference();
private function onSaveText():void
{
fileReference.save(myText.text,"myText.txt");
}

How do I get files in my own file format to have its own dynamic icon?

Our application has a file format similar to the OpenDocument file format (see http://en.wikipedia.org/wiki/OpenDocument) - i.e. zipped with a manifest file, a thumbnail image, etc.
I notice that OpenOffice files have a preview image of the Open Office file as their icons, both in Windows and in Linux. Is there some way to accomplish this for our files: i.e. I want a dynamic icon based on the internal thumbnail.png?
Edit 1 Wow, thanks for all the quick answers. Thumbnailer looks great for the GNOME world. Windows I'll be looking into those links, thanks. As for the comment question: programmatically OR via our installer.
Edit 2 Oh, forgot Mac. How about on the Mac? (Sorry Mac lovers!) Also are there any links or info for how OpenOffice does their IconHandler stuff - since ours would be very similar?
Windows
What you need is an Icon Handler, also known as a Thumbnail Handler. Here is an example written as an active x control.
Another resource is to look up Property Handlers, which should also point to you to the latest and greatest way of having dynamic meta data handled correctly in windows.
These are dynamic solutions - they aren't needed if you just want an icon associated with all your files - they are only used when you want windows explorer to display an icon based on what's in the file, not just the extension, and when the file changes the icon is updated to reflect the changes. It doesn't have to be an image of the file itself, either, the thumbnail handler can generate any image based on the file contents.
The property handler updates other metadata, such as song or video length, so you can use all the metadata Windows Explorer supports.
Regarding MAC support, this page says, "The Mac and Windows operating systems have different methods of enabling this type of thumbnail, and in the case of the Mac OS, this support has been inconsistent from version to version so it hasn't been pursued [for Adobe InDesign]."
OS X
Icons for Mac OSX are determined by the Launch Services Database. However, it refers to a static icon file for all files handled by a registered application (it's not based on extension - each file has meta data attached that determines the application to which it belongs, although extensions give hints when the meta data doesn't exist, such as getting the file from a different OS or file system)
It appears that the dynamic icon functionality in OSX is provided by Finder, but searches aren't bringing up any easy pointers in this direction. Since Finder keeps changing over time, I can see why this target is hard to hit...
Gnome
For Gnome you use a thumbnailer. (thanks Dorward)
This is an extraordinarily simple program you write, which has 3 command line arguments:
input file name, the file you are describing with the thumbnail (or URI if you accept those instead)
output file name, where you need to write the PNG
size, a number, in pixels, that describes the maximum square image size you should produce (128 --> 128x128 or smaller)
I wish all systems were this simple. On the other hand this doesn't support animation and a few other features that are provided by more difficult to implement plugins on other systems.
KDE
I'm a bit uncertain, but there are a few pointers that should get you started. First is that Konqueror is the file manager and displays the icons - it supports dynamic icons for some inbuilt types, but I don't know if these are hardcoded, or plugins you can write. Check out the Embedded Components Tutorial for a starting point.
There's a new (ish?) feature (or planned feature...) called Plasma which has a great deal to do with icons and icon functionality. Check out this announcment and this initial implementation.
You may need to dig into the source of Konqueror and check out how they did this for text files and others already implemented.
-Adam
Mac OSX since version 10.5 …
… has two approaches:
Your document is in the standard OSX bundle format and has a static image
This can be done by creating a subfolder QuickLook and placing the Thumbnail/Preview.png/tiff/jpg inside.
Everything else needs a QuickLook generator plugin which can be stored in either /Library/QuickLook ~/Library/QuickLook or inside the YourApp.app/Contents/Library/QuickLook Folders.
This generator is being used to create Thumbnails and QuickLook previews on the fly. XCode offers a template for this. The template generates the needed ANSI C files which have to be implemented. If you want to write Object-C code you have to rename the GenerateThumbnailForURL.c and GeneratePreviewForURL.c to GenerateThumbnailForURL.m and GeneratePreviewForURL.m (and read the Apple Devel Docs carefully ;) )
Simple zip container based demo:
You will have to add the Cocoa.framework and Foundation.framework to your project
In your GenerateThumbnailForURL.c (this is partly out of my head - so no guarantee that it works out of the box ;) ):
#include <Cocoa/Cocoa.h>
#include <Foundation/Foundation.h>
OSStatus GenerateThumbnailForURL(void *thisInterface, QLThumbnailRequestRef thumbnail, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options, CGSize maxSize)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
/* unzip the thumbnail and put it into an NSData object */
// Create temporary path and writing handle for extraction
NSString *tmpPath = [NSTemporaryDirectory() stringByAppendingFormat: [NSString stringWithFormat: #"%.0f.%#" , [NSDate timeIntervalSinceReferenceDate] * 1000.0, #"png"]];
[[NSFileManager defaultManager] createFileAtPath: tmpPath contents: [NSData alloc] attributes:nil];
NSFileHandle *writingHandle = [NSFileHandle fileHandleForWritingAtPath: tmpPath];
// Use task to unzip - create command: /usr/bin/unzip -p <pathToFile> <fileToExtract>
NSTask *unzipTask = [[NSTask alloc] init];
[unzipTask setLaunchPath: #"/usr/bin/unzip"];
// -p -> output to StandardOut, added File to extract, nil to terminate Array
[unzipTask setArguments: [NSArray arrayWithObjects: #"-p", [(NSURL *) url path], #"Thumbnails/thumbnail.png", nil]];
// redirect standardOut to writingHandle
[unzipTask setStandardOutput: writingHandle];
// Unzip - run task
[unzipTask launch];
[unzipTask waitUntilExit];
// Read Image Data and remove File
NSData *thumbnailData = [NSData dataWithContentsOfFile: tmpPath];
[[NSFileManager defaultManager] removeFileAtPath: tmpPath handler:nil];
if ( thumbnailData == nil || [thumbnailData length] == 0 ) {
// Nothing Found. Don't care.
[pool release];
return noErr;
}
// That is the Size our image should have - create a dictionary too
CGSize size = CGSizeMake(256, 256);
NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:size.width],kQLPreviewPropertyWidthKey,
[NSNumber numberWithInt:size.height],kQLPreviewPropertyHeightKey,
nil];
// Get CGContext for Thumbnail
CGContextRef CGContext = QLThumbnailRequestCreateContext(thumbnail, size, TRUE, (CFDictionaryRef)properties);
if(CGContext) {
NSGraphicsContext* context = [NSGraphicsContext graphicsContextWithGraphicsPort:(void *)CGContext flipped:size.width > size.height];
if(context) {
//These two lines of code are just good safe programming…
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:context];
NSBitmapImageRep *thumbnailBitmap = [NSBitmapImageRep imageRepWithData:thumbnailData];
[thumbnailBitmap draw];
//This line sets the context back to what it was when we're done
[NSGraphicsContext restoreGraphicsState];
}
// When we are done with our drawing code QLThumbnailRequestFlushContext() is called to flush the context
QLThumbnailRequestFlushContext(thumbnail, CGContext);
// Release the CGContext
CFRelease(CGContext);
}
[pool release];
return noErr;
}
Info.plist
You will have to modify your info.plist file too - when you open it up it has a lot of fields pre-set. Most of them are self-explaning (or will not have to be changed) but I had to add the following structure (copy paste should do - copy the text, go into the plist editor and just paste.):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>com.pkware.zip-archive</string>
</array>
<key>UTTypeDescription</key>
<string>i-net Crystal-Clear Report File</string>
<key>UTTypeIconName</key>
<string>generic</string>
<key>UTTypeIdentifier</key>
<string>com.company.product</string>
<key>UTTypeReferenceURL</key>
<string>http://your-url.com</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>$fileEXT$</string>
</array>
</dict>
</dict>
</array>
</plist>
This will register your filetype $fileExt$ and tell the system that your filetype is a zipy format type. A nice refference, that I used here is the QuickLook IPA Plugin from googlecode
In Windows, what you need is to implement an Icon Handler. I did this many moons ago and it is not difficult as long as you know the basics of COM.
See: http://msdn.microsoft.com/en-us/library/bb776857(VS.85).aspx
For Gnome you use a thumbnailer.
for WINDOWS try this:
http://www.easydesksoftware.com/news/news12.htm
Executables have the icon inside the file (potentially multiple) as a "resource".
Data files pick up an icon based on file association.
If you want a custom icon per file that is much harder. you either need too fool the OS into thinking it is an executable and embed the icon as a resource in the file, or deep link into the OS to override the default icon selection routine.
I think, "custom own" icon can have only PE files in windows. Every other icons for file extensions are stored in windows registry.
For specification of PE file, you can look at An In-Depth Look into the Win32 Portable Executable File Format and Peering Inside the PE: A Tour of the Win32 Portable Executable File Format.
How it works in other OS, I don't know :/.
I don't know about Linux, but for Windows you can start here:
http://msdn.microsoft.com/en-us/library/bb774614.aspx
Edit: I think this interface is for the thumbnails shown in thumbnail view, not icons. Sorry for wasting your time.

Resources