Get the duration of all the files inside a directory mp3

Hi all

I'm working on a little project with swing. Because I need an MP3 inside my swing application, I found a solution really good with JavaFX 2. I never worked with JavaFX, to this effect, it seems a bit strange on some parts.
Anyway.

I created a button on my request and as soon as someone clicks on this button, the application should scan recursively a directory of mp3 files and store information of artist, title and track length in a database.

The mp3 player I created is based on the example on this page:
http://www.java2s.com/code/Java/JavaFX/Mp3playerwithmetadataviewandcontrolpanel.htm

I understand the source of most of the regions, but some behaivors are not really clear for me. My thoughts to get the full length of the mp3 file has been

media.getDuration
or
mediaplayer.getTotalDuration

but the two results are NaN values 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 for this listening port on the mediaplayer
mp.totalDurationProperty().addListener(new TotalDurationListener());
I can image that the mediaplayer can "host" several objects somewho media and the listener is called as soon as a new media will be added to the mediaplayer in order
the calculation of the total time.

When this listener is exactly called and is there any other way to get the total length of the mp3 file?


Here is a minimal example that 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 headset for the metadata to be changed in order to get the metadata?
media.getMetadata().addListener(new MapChangeListener<String, Object>()
Why can't I call something like
media.getMetadata ()-> returns a map full?

The problem of metadata is not included in the above example.


Sorry for my English, but I hope that everyone can understand the question.

Many greetings,
Hauke

The class nature of the media is that it accesses it asynchronously. This means that when you create an instance of it and then immediately question him, the data that you might want to not available yet. It's all in the Javadoc, see the doc for the media:

The media information are obtained from asynchronously and are therefore not necessarily available immediately after the instantiation of the class. However, all the information should be available if the instance has been attached to a MediaPlayer and this player is passed to the status of MediaPlayer.Status.READY

So you can engage the media in a MediaPlayer and then wait until he goes to the READY State and then read the length of the media.

On your 2nd question, getMetadata() turns over a card. Loop just through him:

  for(Map.Entry entry : media.getMetadata()) {
    // etc
  }

However, the same restrictions apply as with the media - you'll probably have to wait before information is available - that's why the listener approach works because it will inform you as soon as information is added to the map.

Tags: Java

Similar Questions

  • How can I get all the file in a directory name?

    Purpose:

    Try to get all the file in a directory name.

    My code:

    FileConnection fconn = (fileDirectory) Connector.open (FileConnection);
    Listing files = fconn.list ();
    Listing files = fconn.list ("*", true); Try
    _SCREEN.updateDisplay (files); txt shows unreadable.
    String filename = fconn.getName ();
    _SCREEN.updateDisplay1 (fileName); Show WMMS.

    Try using fileconnection.getName (). -->, But fail.

    Could someone give a tip to solve the problem?

    Thank you for your attention,

    You cannot print just an enumeration.
    It is a collection that contains objects, in this case of strings, as you can see on http://www.blackberry.com/developers/docs/7.1.0api/javax/microedition/io/file/FileConnection.html#li...

    You can use a while construct to browse the enum, as:
    While (files.hasMoreElements ()) {}
    System.out.println (files. NextElement());
    }
    (do not know if you do not cast explicitly to a string for sysout, iirc)

  • My text box is frozen and has a dotted around her line, how can I get the cursor inside?

    My text box is frozen and has a dotted around her line, how can I get the cursor inside? I work in Indesign CS3, I wrote a page of A4 format with a unique and with a large amount of text inside text box. In the end, I brought a JPEG in the page. Now they have a thin line dotted around them and appear "frozen." I have not seen the dotted line instead of the line before usual text box.

    Points: The text box is not locked, the layer is not locked. Nothing on the page goes live with command + A to select.

    It happened between the Time Machine backups so that I can not restore.

    All I need are the captured keystrokes.

    What can happen when you put the JPEG, I myself can I have moved that file folder, a larger file, on the desktop, then placed the JPEG.

    Re-opening Indesign didn't work; restart did not work.

    Solutions appreciated.

    The dotted lines mean that your items are on a master page and not a document page.

  • Is it possible to get the files for windows vista, so I can reinstall my system?

    Hello

    Im a user of linux on one machine HP Pavilion dv5-1095eo leisure. IM tired to restart my machine to run a windows OS, so is possible for me to get the files for windows vista. I got the windows key attached under the computer and I don't have any windows CD when I brought the machine.

    Hello:

    You can do your own installation disc Vista too if you wish.

    If you can read your 25-character product key MS, you can make your own Windows Vista installation disc. You just download the 3 files you need on the link below and read all the instructions to create a Setup bootable DVD disk using imageburn.

    When I went to compile the ISO file, ImageBurn gave a message on a WIM file, file and ISO, and if I wanted to burn it in a different format.

    I selected no, make the ISO file.

    It was not so hard to do. I burned both the disk of 64-bit and 32-bit disk in case I ever need them.

    I tested both of them (just before going forward with the actual facility) and they seem to work perfectly.

    Apparently, when you enter the product key, he knows which version of Vista you have.

    http://en.community.Dell.com/support-forums/software-OS/w/microsoft_os/3317.2-3-Microsoft-Windows-VI...

    After you have successfully installed vista, you can download the drivers you need your PC support and driver page.

    Paul

  • How can I get the file name of a report, I have just stored in the cache

    I would like to be able to get the file name of the report that is stored in the cache directory.

    When a report is created from forms to help

    SET_REPORT_OBJECT_PROPERTY (v_report_id, report_desname, 'fubar.pdf');

    In the cache directory a file is created something like fubarABC123DE.pdf. I guess that part of ABC123DE is the cache key.

    I want to be able to read this file from another process. This process cannot use http, so I can't pass the URL. However, I would still be able to access by using the URL.

    Is all the same to get at the file name?

    The answer is, according to management, you can get the name of the file in the cache, so if you want to access the file you need to store somewhere else.

  • I have just reactivated Dreamweaver on a new computer.  How can I get the files FROM my website ON my computer so I can edit/update using Dreamweaver.

    I have just reactivated Dreamweaver on a new computer.  How can I get the files FROM my website ON my computer so I can edit/update using Dreamweaver?

    If your old machine still works, export your definition of original site to a portable player, copy in your new machine and then import the site definition to the new machine. The definition file will have the extension .ste

    Create an empty folder on your new machine.

    Define a 'new' web site on your new machine to point to the new local root folder.

    Log your server and download all of the subfolders and files in the folder root from the server to the new local root folder.

  • I am trying to reinstall windows xp from disk but it only gets up to this request then for service pack 1 disc when I press on enter I get the file 'asms' on windows xp pro Service Pack1 necessary

    I am trying to reinstall windows xp from disk but it only gets up to this request then for service pack 1 disc when I press on enter I get the file 'asms' on windows xp pro service pack 1 cd needed someone had this problem and managed to solve it thanks a lot

    Hello

    Thanks for joining us on the Microsoft Community.

    According to the description of the problem you are facing problems with reinstalling Windows XP Professional, and you are to be invited to insert the Service Pack 1 drive to complete the installation.

    To help you to propose measures to solve the problem, I would appreciate if you could answer the following questions:

    1. did you uninstall Windows XP Service Pack 1 prior to reinstalling Windows XP?

    2. what was the installed Service Pack earlier?

    You may need to uninstall Windows XP Service Pack 1 first and then perform the reinstallation of Windows XP and to check if the installation goes smoothly.

    Please see the following articles for more information about uninstalling Windows XP Service Pack 1:

    How to manually remove Windows XP Service Pack 1

    http://support.Microsoft.com/kb/329015

     

    How to remove folders from Windows XP Service Pack 1

    http://support.Microsoft.com/kb/329260?WA=wsignin1.0

    Hope this information helps. Please come back for any clarification on this or any issue of Windows. We will be happy to help you.

  • Cannot get the file to be imported.

    I tried the method of JoseIbarra - I did as suggested but cannot get the file to be imported in the services file. He never asked me if I wanted to add the information in the registry, so it is still on the office. Don't know what to do from here.

    Please stick to the initial conversation.

    Is this you speak of course (*first conversation*):
    http://answers.Microsoft.com/en-us/Windows/Forum/windows_xp-system/how-do-i-get-print-spooler-back-into-my-Windows-XP/ed014329-1bd3-458d-9C93-bbb306fc731f

    You also made this one:
    http://answers.Microsoft.com/en-us/Windows/Forum/windows_xp-system/print-spooler/c4610093-a96f-4476-B263-eecf5b8fc339

    (but please do not reply to this one...)

    And this one:
    http://answers.Microsoft.com/en-us/Windows/Forum/windows_xp-system/continuation-of-print-spooler-problem/0e885d7b-3e64-42ee-A248-9d9f2a8e26c5

    (Even once - keep the * first conversation * going.)  Written on it.  Show how this conversation continues spreading around.)

    BTW - my suggestion has not changed.  I still think that you get just around issues that still exist, probably, by fixing the little things you need at a given time.

    Backup important files/folders (for you) (including documents, photos, music, Favorites, Internet favorites, files installable application, serial numbers, product keys, spreadsheets, you saved to the desktop email, etc.) and wipe the disc completely - I'd even a zero writing on the disc (formatting) before installing the operating system from the original installation media.  Then install your applications and restore your files.

    As to what they were asked to do... Always seems that you saved the file as a *. TXT file and not a *. REG or there is much more wrong with your machine (see my suggestion above.)

    Visit this web page to look at the photo on the left (a first) to see the screenshot of the possible is the desktop icons and let us know if it looks like the left or right of each photo version (answer here or in the longer conversation.)  * Ignore the first part of the file name - as you might have named something else than "addspooler."

    To check if you saved incorrectly or if there is something wrong with your system (or two) - right click on the file you saved and choose 'Properties' from the menu you get.  Under the 'Général' tab, she said, "file Type: registration entries (.reg)" and "opens with: Registry Editor" or something similar?  Visit this web page to look at the picture on the right (second) to see the screenshot of the possible look at the windows of the property and let us know if it looks like the left or right of each photo version (answer here or in the longer conversation.)  * Ignore the first part of the file name - as you might have named something else than "addspooler."

  • I can't get the file "Delete empty" vacuum. He has worked in the past. I have Vista and use Windows Mail.

    I can't get the file "Delete empty" vacuum.  He has worked in the past.  I have Vista and use Windows M

    Duplicate of:
    http://answers.Microsoft.com/en-us/Windows/Forum/windows_vista-networking/empty-delete-mail-function-doesn ' t/43a2d3a8-5b7a-e011-9b4b-68b599b31bf5

  • Smartphones blackBerry synchronization error - failed to get the file

    BlackBerry Torch 9860 software v 7.0 Bundle 2406

    Can someone help me with this error message of synchronization:

    "An error occurred during an attempt to access a record of the database of the device."

    Details below.

    engine 08:46:51.759 waiting for the user to input - message WPF event for messageId 15003 raised read 310 records
    08:46:51.762 engine work - full message event for messageId 15003 read 310 records
    08:46:51.859 CBBTransBase::GoToRecord - could not get the file FFFFFB45
    08:46:51.860 error information: 18008 (00004658) (KnownErrorWithLocalizedText), Description: an error occurred during an attempt to access a record of database device., File:.\BBTransBase.cpp, line: 736
    08:46:51.860 CRSyncUtil::GetTranslator: FeedProfileShim2Trans (responsible Trans) BlackBerry
    08:46:51.860 CRSyncUtil::FeedProfileShim2Trans: returns 0
    08:46:51.860 CRSyncUtil::LogFatalTransError: 'GoToRecord()' 'RimBB' translator for the "Contacts" application API returned empty error
    08:46:51.860 CBBTransContact::Close - clean temporary fixation for contacts files
    08:46:51.862 CBBTransBase::Close - Mode: 4
    08:46:51.862 CBBTransBase::Close - commit the change log
    08:46:51.862 CBBTransBase::Close - save information from source database device
    08:46:51.976 CBBTransBase::Close - peripheral close database
    08:46:51.976 CBBTransChangeLog::Close - close change log db. Record count: 474. Db file: C:\Users\Bob\AppData\Local\Research in Motion\BlackBerry Desktop\XCPCSync.OEM\SyncSDK.209.601\Translators\RimBB\Contract{8BCB53647E24F3BB61A8E73C4FDAB}.adt
    08:46:51.990 enter COLTransBase::Close - Mode - 4
    Synchronization of end of 08:46:51.991 with error 2

    Glad to hear it is working now.

    Don't forget to let us know if you have any other questions.

  • How to get the files in the subfolder by Apple Script

    say application 'Finder '.

    the value ArtFolder to choose a folder with guest "Select the folder of Art: - > >".

    set ChapNameFolders to the folder list ArtFolder without invisible

    Repeat with ChapFolder in ChapNameFolders

    set ArtFiles for files in ChapFolder

    display the dialog ( )County ArtFiles( )


    Repeat with ArtFileItem in ArtFiles

    value FileInfo info for ArtFileItem

    set File name to the of ArtFileItem name

    if folder of FileInfo is true then

    view the dialog box FileName as string

    end if

    end Repeat

    end Repeat

    end say

    ===========================================>>

    I used code above to get the files in the subfolder, but it does not, it will fail in second REPEAT & do not get the files in the subfolder...

    Can someone help me solve this problem...

    Thank you.

    My problem has been resolved by this code: -.

    say application 'Finder '.

    the value ArtFolder to choose a folder with prompt "select Art Folder :---> >.

    Repeat with ChapFolder in (get each folder from the folder ArtFolder)

    Repeat with ArtFile in (get each file from the folder ( as aliasChapFolder))

    display the dialog box ArtFile string

    end Repeat

    end Repeat

    end say


    Thank you...

  • Dreamweaver CC 2015 offers to get the files that are not in my root folder

    Dreamweaver CC 2015 offers to get the files, but when I manually check the folder, where it shows some files during the synchronization process, there is nothing. Why?

    Clear your cache.

    Clear Cache corrupted in DW

    http://forums.Adobe.com/thread/494811

    Nancy O.

  • I can't get the file number I need for the license transfer process. Help, please.

    I can't get the file number I need for the license transfer process. Help, please.

    To the link below, click on the still need help? the option in the blue box below and choose the option to chat...
    Make sure that you are logged on the Adobe site, having cookies enabled, clearing your cookie cache.  If it fails to connect, try to use another browser.

    Get help from cat with orders, refunds and exchanges (non - CC)
    http://helpx.Adobe.com/x-productkb/global/service-b.html ( http://adobe.ly/1d3k3a5 )

  • Looking for some practice files for video in line/book of "Adobe Photoshop CS5 Extended: Essentials. I use the tutorial via membership in Safari book online and the files are not available on Safari.  Do you know where I can get the files?

    Looking for some practice files for video in line/book of "Adobe Photoshop CS5 Extended: Essentials. I use the tutorial via membership in Safari book online and the files are not available on Safari.  Do you know where I can get the files?

    Looks like the manufacturer was "Total Training. I can't find the title to Adobe.com

    http://totaltraining.com/store/Photoshop-CS5-extended-Essentials/

  • I get an error message 205, how do I get the file to download and recognize as legitimate?

    I get an error message 205, how do I get the file to download and recognize as legitimate?

    Help creating cloud / cloud creative applications download error

    http://helpx.Adobe.com/creative-cloud/KB/error-downloading-CC-apps.html

Maybe you are looking for