Get the duration of all mp3 files inside a directory

Hello everyone,
I am working on a little project done with swing. Since I need an mp3 player inside my swing application, I found a really good solution with JavaFX 2. I have never worked with JavaFX before, therefor it seems to me a little bit strange on some parts.
Anyway.
I created a button on my application and as soon as somebody presses that button, the application should scan recursivly a unique directory for mp3 files and store the information of artist, title and track length into a database.
The mp3 player I created is based on the example from this page:
http://www.java2s.com/Code/Java/JavaFX/Mp3playerwithmetadataviewandcontrolpanel.htm
I understand the source code for most parts, but some behaivors are not really clear to me. My thoughts about getting the complete length of the mp3 file was
media.getDuration
or
mediaplayer.getTotalDuration
but both results are NaN if I call .toMillis();
Instead I need to create a listener (why?)
private class TotalDurationListener implements InvalidationListener {
    @Override
    public void invalidated(Observable observable) {
      final MediaPlayer mediaPlayer = songModel.getMediaPlayer();
      final Duration totalDuration = mediaPlayer.getTotalDuration();
      totalDurationLabel.setText(formatDuration(totalDuration));
  }and register this listener on the mediaplayer
mp.totalDurationProperty().addListener(new TotalDurationListener());I can image that the mediaplayer can "host" several media objects somewho and the listener is called as soon as a new media will be added to the mediaplayer in order
the calculate the overall duration.
When is this listener exactly called and is there no other ways to get the total length of the mp3 file?
Here is a minimal example which should work without any external libs
package de.hauke.schwimmbad.application.playground;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.paint.Color;
import javafx.util.Duration;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.UIManager;
public class Testing10 extends JFrame {
     private MediaPlayer mediaPlayer;
     private final ReadOnlyObjectWrapper<MediaPlayer> mediaPlayerWrapper = new ReadOnlyObjectWrapper<MediaPlayer>(
               this, "mediaPlayer");
     public static void main(String[] args) {
          try {
               UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
               new Testing10();
          } catch (Exception ex) {
               System.out.println(ex);
     public Testing10() {
          super();
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setLayout(null);
          setSize(500, 500);
          setTitle("Testing");
          setLocationRelativeTo(null);
          setResizable(false);
          JButton button = new JButton("Scan");
          button.setBounds(10, 10, 150, 30);
          add(button);
          button.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent arg0) {
                    scan();
          final JFXPanel fxPanel = new JFXPanel();
          fxPanel.setBounds(30, 80, 300, 300);
          add(fxPanel);
          Platform.runLater(new Runnable() {
               public void run() {
                    initFX(fxPanel);
          setVisible(true);
     private void scan() {
          File directory = new File("C:\\dev\\mp3");
          List<File> mp3Files = new ArrayList<File>();
          for (File file : directory.listFiles()) {
               if(file.getName().endsWith("mp3")) {
                    mp3Files.add(file);
          for (File file : mp3Files) {
               System.out.println(file.getAbsoluteFile());
               getLength(file);
     private Duration getLength(File file) {
          if(mediaPlayer != null) {
               mediaPlayer.stop();
          final Media media = new Media(file.toURI().toString());
          mediaPlayer = new MediaPlayer(media);
          mediaPlayerWrapper.setValue(mediaPlayer);
          if(media.durationProperty()==null) System.out.println("durationProperty ist null");
          if(media.durationProperty().get()==null) System.out.println(".get() ist null");
          System.out.println("---> " + media.durationProperty().get().toMillis());
          return media.getDuration();
     private void initFX(JFXPanel fxPanel) {
          BorderPane root = new BorderPane();
          Scene scene = new Scene(root, Color.ALICEBLUE);
          fxPanel.setScene(scene);
}The other question is why do I need a listener for the meta data to be changed in order to get the meta data?
media.getMetadata().addListener(new MapChangeListener<String, Object>()Why can't I call something like
media.getMetadata() --> returns a filled map?
The metadata problem is not included inside the example from above.
Sorry for my english but I hope everybody can understand the issue.
Many greetings,
Hauke

The nature of the Media class is that it accesses it asynchronously. This means that when you create an instance of it, and then immediately query it, the data you want may not be available yet. This is all in the Javadoc, see the doc for Media:
The media information is obtained asynchronously and so not necessarily available immediately after instantiation of the class. All information should however be available if the instance has been associated with a MediaPlayer and that player has transitioned to MediaPlayer.Status.READY statusSo you could associate the Media with a MediaPlayer, and then wait until it goes to the Status READY, and then read the length of the Media.
As for your 2nd question, getMetadata() returns a Map. You can just loop through it:
  for(Map.Entry<String, Object> entry : media.getMetadata()) {
    // etc
  }However, the same restrictions apply as with Media -- you will probably need to wait before the information is available -- that's why the Listener approach works, because it will notify you as soon as the information is added to the map.

Similar Messages

  • Getting the path of  a resource file inside the context

    I am trying to migrate some of our applications running on OracleApplicaiton Server. We have data resource xml file needs to use in the applicaiton. In Oracle Application server we used to give the actual path of the xml file to load the xml file to the parsers since we know the path of the directories after deploying the application as an ear file. How can I get the path of the files in weblogic after deployment. If this is not supported what is the alternative to get the relative path of that xml file to load in ? The xml file is in the root folder of the context.
    THanks
    Suneesh

    Hi Suneesh,
    Please try enabling the <show-archived-real-path-enabled> Tag to TRUE ...And then everything will work fine with the following code:
    context.getRealPath()
    At domain level in config.xml. For example:
    <web-app-container>
    <show-archived-real-path-enabled>true</show-archived-real-path-enabled>
    </web-app-container>
    *****OR *****
    At the web app level in weblogic.xml. For example:
    <container-descriptor>
    <show-archived-real-path-enabled>true</show-archived-real-path-enabled>
    </container-descriptor>
    For Archived Applications , It is always a best practice to use the getResourceAsStream() rather than using getResource().......Below code snippet should workout in 99% cases
    InputStream stream=this.getClass().getClassLoader().getResourceAsStream("someXMLorPropfile.properties");
    Thanks
    Jay SenSharma
    http://middlewaremagic.com/weblogic/?p=408  (Middleware Magic is Here)

  • How can i get the path to config folder placed inside the jar file?

    Hi i have developed an RCP application using eclipse.
    In my application config directory is there.
    When i export my RCP application as JNLP Project the jar file is created which contains config folder inside it.
    When i download the application using java web start , how can i get the path to config folder placed inside the jar file?
    Will the config folder exists in local cache in my system?
    Help needed.
    -Deepak

    -- This works in CS6:
    tell application "Adobe InDesign CS6"
      set myDocument to active document
      set selectedRectangles to selection of myDocument
      set theGraphicsLink to file path of item link of (graphic 1 of (item 1 of selectedRectangles))
    --> "Macintosh HD:folder/folder/filename.tif"
    end tell

  • How do U to get the names of all files in a directory?

    Is there a simple way to get all names of the files in a directory and put them in an array of Strings? Sounds simple, but I don't have a clue how to do this. Thanks.

    Hi Kindoo,
    Create a instance of File object using the path of the Directory
    File fileDir = new File(directoryPath);
    To get the List of all the files in the directory use
    String[] strFiles = fileDir.list();
    This will solve your problem,
    Cheers
    Nagaraj

  • I have CS4 In design but when I try to open a certain file I get the answer that all plug in´s is not in my program. How can I update my plug ins?

    I have CS4 In design but when I try to open a certain file I get the answer that all plug in´s is not in my program. How can I update my plug ins?

    <moved from Downloading, Installing, Setting Up to InDesign>

  • Use apple script to get the duration of soundfiles and send the info to FileMaker

    I have close to 6000 soundfiles in approx. 20 subfolders of a folder called soundarchive and a FileMaker DB of all those files. Here's what I'd like to do. Get the duration of each file and send it to the "duration" field of the matching FMrecord. I don't know a lot about AppleScript (or programming anything apart from my HD recorder), what I do know is that a script will save me from a week of copy-pasting the info manually. I found a script by hubionmac  that does the first part (for one file) it goes like this:
    set aFile to choose file
    tell application "Finder" to set filename to name of aFile
    set AppleScript's text item delimiters to " = "
    set duration to text item 2 of (do shell script "mdls -name kMDItemDurationSeconds " & quoted form of (POSIX path of aFile))
    set AppleScript's text item delimiters to "."
    set total_seconds to text item 1 of duration
    set AppleScript's text item delimiters to ""
    set showsec to (total_seconds as integer) mod 60
    set showmin to (total_seconds as integer) div 60
    display dialog filename & return & return & "Duration:" & return & showmin & " min " & showsec & " sec"
      So this is for one file. How do I get the information for the other 5000+ files and send it to the FileMaker DB. Obviously the "display dialog" won't do so it'll have to be changed to something like "get". How do I proceed from here?

    Hi Preetha7,
    I found one automated SQL Server Health Check Solution which may meet your needs. The daily health checks include checking CPU utilization, database status, available disk space, network packet errors, database backup status, and more. For more detail about
    this solution, please refer to the following article:
    http://sqlmag.com/database-administration/automated-sql-server-health-check-solution
    In addition, if you want to write your own script to perform a quick health check of SQL Server using PowerShell, please refer to the following article:
    http://blogs.technet.com/b/heyscriptingguy/archive/2011/07/25/use-powershell-to-monitor-your-sql-server-performance.aspx
    If you have any question, please feel free to let me know.
    Regards,
    Jerry Li

  • How can we get the artset from a .ai file without opening it?

    Hello All,
    I have one .ai file, lets say sample.ai file. located in C drive. so the complete file path is "C:\Sample.ai".
    and lets assume the sample.ai file has one traingle shape(3 path type arts) in it.
    Now I want to get the 3 path arts (artset)  from sample.ai file without opening it in AI.
    The function protoype is like below
    AIArtSet& artSet GetArtSetFromAFile( ai::FilePath& filePath );
    Is there any API like above function in AI? or is it possible to get the art(s) from a file without opening it in AI?

    Not to my knowlege. The API only operates on active documents as far as I know.

  • Query to get the data of all the columns in a table except any one column

    Can anyone please tell how to write a query to get the data of all the columns in a table except one particular column..
    For Example:
    Let us consider the EMP table.,
    From this table except the column comm all the remaining columns of the table should be listed
    For this we can write a query like this..
    Select empno, ename, job, mgr, sal, hiredate, deptno from emp;
    Just to avoid only one column, I mentioned all the remaining ( 7 ) columns of the table in the query..
    As the EMP table consists only 8 columns, it doesn't seem much difficult to mention all the columns in the query,
    but if a table have 100 columns in the table, then do we have to mention all the columns in the query..?
    Is there any other way of writing the query to get the required result..?
    Thanks..

    Your best best it to just list all the columns. Any other method will just cause more headaches and complicated code.
    If you really need to list all the columns for a table because you don't want to type them, just use something like...
    SQL> ed
    Wrote file afiedt.buf
      1  select trim(',' from sys_connect_by_path(column_name,',')) as columns
      2  from (select column_name, row_number() over (order by column_id) as column_id
      3        from user_tab_cols
      4        where column_name not in ('COMM')
      5        and   table_name = 'EMP'
      6       )
      7  where connect_by_isleaf = 1
      8  connect by column_id = prior column_id + 1
      9* start with column_id = 1
    SQL> /
    COLUMNS
    EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,DEPTNO
    SQL>

  • How to get the Real Path of a file which is accessed  by URL?

    iam using tomcat6.0.
    I have a file xyz.xml at the top of the webapplication HFUSE which i can able to access by URL
    http://localhost:8080/HFUSE/xyz.xml
    My problem is how to get the realpath of the file "xyz.xml" for reading and writing purposes.
    I tried various things but i could not able to successfully solved the problem?
    1) File f = new File("/xyz.xml");
    print(f.getAbsolutePath()) ============== it is not fetching the file @ http://localhost:8080/HFUSE/xyz.xml rather it is creating a file
    at the root of the drive where eclipse is running.
    2) File f = new File("xyz.xml");============> this is also not working , it is creating the file xyz.xml in the eclipse directory ..................
    Can anyone please guide on this problem?

    RevertInIslam wrote:
    If you want your context root(i.e HFUSE)
    use this:
    request.getContextPath() //where request is HttpServletRequest object to get the needful path.
    e.g:
    File f = new File(request.getContextPath()+"/xyz.xml");//it will create the file inside HFUSE.
    Hope this helps.
    Regards
    BWrong. The File constructor expects an absolute filesystem path. The HttpServletRequest#getContextPath() doesn't return the absolute filesystem path, it only returns the relative path from the current context root. Use ServletContext#getRealPath() instead, it returns the absolute filesystem path for the given relative path from the current context root.
    File file = new File(servletContext.getRealPath("/"), "xyz.xml");

  • Getting the page size in PDF file

    i want know how do get the page size in PDF file befor placing every page in document
    for example height=297 mm And width=210mm

    This script:
    http://indesignsecrets.com/zanelli-releases-multipageimporter-for-importing-both -pdf-and-indd-files.php
    answers all your questions.
    Peter

  • I d/l your mozilla firefox today and now I get the error 0x80070002 all the time...how do I fix that?

    I downloaded mozilla firefox today and now I get the error 0x80070002 all the time, and I cannot use system restore because of it. How do I fix that so that my computer works right again. I was restoring because after I d/l your mozilla today, I lost all of my contacts in my msn email...just been tearing my hair out over this and it is soo darn frustrating. Tell me how to fix this. Marilyn

    Hi,
    The error is totally unrelated to Firefox. Please see [http://support.microsoft.com/kb/910336 this]. The [http://answers.microsoft.com/en-us Windows OS forum] will also be helpful.
    Please also check the downloaded file by right-clicking > Properties > Digital Signatures, which should say '''Mozilla Corporation''' and '''This digital signature is ok''' in '''Details'''. You can download Firefox from a known site like e.g. https://www.mozilla.org/en-US/firefox/new/
    You can try to Reset Firefox which would hopefully display the missing features, all (contacts, emails, settings etc.) of which are actually stored at the MSN site and are temporarily displayed by Firefox every time the site is accessed.
    The Reset Firefox feature can fix many issues by restoring Firefox to its factory default state while saving your essential information.
    Note: ''This will cause you to lose any Extensions, Open websites, and some Preferences.''
    To Reset Firefox do the following:
    #Go to Firefox > Help > Troubleshooting Information.
    #Click the "Reset Firefox" button.
    #Firefox will close and reset. After Firefox is done, it will show a window with the information that is imported. Click Finish.
    #Firefox will open with all factory defaults applied.
    Further information can be found in the [[Reset Firefox – easily fix most problems]] article.
    Did this fix your problems? Please report back to us!

  • How do I get a list of all missing files in a catalog in LR2?

    Is there an easy way to get a list of all missing files for the thumbnails in Lr2? I know the symbol that appears in the upper right corner of any particular photo that is missing its file, but how can I get a list of all such photos for an entire catalog (or at least big chunks of a catalog).
    Thanks.

    You can right click a folder and choose Synchronise - it has a Show Missing Files buttom.
    John

  • Getting the page content as pdf file

    Hi All,
    I have a use case like i need to get the page content as pdf file.
    For this i found xsl file and it's config under the following locations
    /libs/cq/config/rewriter/pdf/transformer-xslt --config of source
    /libs/wcm/core/content/pdf/page2fo.xsl -- xsl file location
    For custamising this functionality i copied both confing node and xsl file under "/apps" .In the Config file i changed source to refer xsl file under /apps.But it's not taking config changes.
    I have looked into http://cqblueprints.com/xwiki/bin/view/CQ+FAQ/How+can+I+configure+the+ PDF+rewriter
    there it's saying like we need to modify the com.day.cq.rewriter.xml.XSLTTransformer class. i am not getting how to modify it.
    I need this urgently
    Thanks,
    Chinna Yadlapalli.

    This script:
    http://indesignsecrets.com/zanelli-releases-multipageimporter-for-importing-both -pdf-and-indd-files.php
    answers all your questions.
    Peter

  • How do I save all mp3 files as an attachable file in text messaging on a G'z One Commando? Some mp3 save as these types of files but I don't how or what I do differently.

    How do I save all mp3 files as an attachable audio file in text messaging on a G'z One Commando? Some mp3 save as these types of files but I don't how or what I do differently.

    In summary, it sounds to me as though the Mac concept of "hidden extension per file" isn't embraced at all by Photoshop.
    So assuming the extension is always visible, what is the easiest way do each of the following (ignoring issues with integration with other apps):
    1.  Save a JPEG as:  abc.jpg
    2.  Save a JPEG as:  abc
    3.  Save a JPEG as:  abc.
    4.  Save a JPEG as:  abc.xxx
    Since it seems to me we still haven't nailed down whether there's a disparity between how this works on Photoshop for Mac vs. PC, I'll answer the above questions for PC:
    1.  File - Save As, choose Format: JPEG, type (replace filename with):  abc
    2.  No difference than 3 on a PC.
    3.  File - Save As, choose Format: JPEG, type:  abc.
    4.  File - Save As, choose Format: JPEG, type:  abc.xxx
    How is it different from the above on a Mac?
    Is there something more complex, such as the sequence of operations, or another system setting, that I didn't cover here?  I normally always keep Explorer set so that file extensions are visible (it's global on a PC).
    -Noel

  • To get the table data into a file in pl/sql developer

    Hi
    i have table with 90k rows, i want to get the table data into a file like excel....
    i executed the select statement it shows only 5k rows because of buffer problem.
    can u please help me any alternative way to get the table data into a file.
    using cursors like that

    Really? excel for 90K rows :)
    face/desk/floor/"Hi and sorry neighbours below, it's me again"
    Err, I see you point, thanks Dang, I completely missed the 90k recs part, I must be getting old or modern ;)
    @Ramanjaneyulu,
    can u please help me any alternative way to get the table data into a file.You can always dump a query to a file, check these:
    http://tkyte.blogspot.com/2009/10/httpasktomoraclecomtkyteflat.html
    How to create Excel file (scroll down when necessary)
    http://forums.oracle.com/forums/search.jspa?threadID=&q=export+to+excel&objID=f137&dateRange=all&userID=&numResults=15&rankBy=10001
    Depending on your database version ( the result of: select * from v$version; ) you might have some other options.

Maybe you are looking for

  • Enhamcement for va01

    Hi experts, I hope u can Resolve this query.......My requirement is in 'XD02' by giving the customer no and the division type. in the next screen in sales document screen and in the billing document tab it will dispaly the payment term tat maintained

  • RTF output

    I have a text to display if there is no information available. So I put this text outside the repeating frame. When I run the report normally it displays fine. But when I generate the output to rtf, the data as well as the text is displayed and they

  • Create a Logical Database Based on Mseg and Bseg

    Hi,   how can i create a Logical database using bkpf,bseg,mkpf,mseg. i need to know , which table is a root node ? could any one help me?    Thanks

  • Bad quality earbuds :(

    hi I have my 5th generation iPod since november, and in february my earbuds started to "lose their skin"... the new generation earbuds, with the soft cover, different from the other ones, that had it in the same plastic as the resto ef the thing... w

  • Has ANYONE successfully connected a printer with Bluetooth?

    I recently purchased a D-Link 120 and was unsuccessful connecting it to my printer with D-Link's 320. I was told by D-Link the -320 will not work with a multifunction printer. I am set to purchase a new printer with a printer adapter from the same ma