简体   繁体   中英

How to use a .mp3 file in java?

I'm using java to try and make an alarm of sorts. I want to input a time and then when it hits zero, play a specific .mp3. The countdown works fine, but when it hits zero and tries to play the mp3, it can't find the file. Advice? I've already searched the site and can't find anything simple enough for me to use (I'm a beginner). Here's what I got so far:

public static void main(String[] args) { 

   int timer;
   File song = new File("C:/Users/N/Documents/Random/Handies/Proj/Song.mp3");

   timer = 1;
   timer*=1;

   while (timer != 0)
   {
     try
     {
       Thread.sleep(1000);
     } catch (InterruptedException e) {}
     timer -= 1;
     System.out.println(timer);
   }  

  if (timer == 0)
    Play(song);    
}

  public static void Play(File song)
  {
    try
    {
      Clip clip = AudioSystem.getClip();
      clip.open(AudioSystem.getAudioInputStream(song));
      clip.start();
    }
    catch (Exception exc)
    {
      exc.printStackTrace(System.out);
    }

  }

With JavaFX you can easily play the MP3 like this:

public class Test extends javafx.application.Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        File file = new File("/path/test.mp3");
        Media media = new Media(file.toURI().toString());
        MediaPlayer mediaPlayer = new MediaPlayer(media);
        mediaPlayer.play();
    }
}

I usually find it hard using AudioSystem for this kind of thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM