-1

I'm trying to play music in Java but I'm unable to solve this.

 package Mplayer; 
 import java.io.File;...

public class Music 
{
private static final String AudioPlayer = null;

public static void main(String[] args)...
public static void playMusic(String filepath) 
{
    InputStream music;
    try 
    {
        music = new FileInputStream(new File(filepath));
        AudioInputStream audios = new AudioInputStream((TargetDataLine) music);
        AudioPlayer.player.start(audios);
    } 
    catch (Exception e) 
    {
        // TODO: handle exception
        JOptionPane.showMessageDialog(null, "Error");
    }
}
}

The player wouldn't work no matter what I change it into.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 2
    You specified `AudioPlayer` as a constant of the type String that does not have a field `player`, so `AudioPlayer.player` won't work. And even if the declared type of this constant would have a `player` field, it would not work because the constant has the value `null`. – howlger Feb 24 '22 at 11:16
  • 2
    This is how you defined AudioPlayer `private static final String AudioPlayer = null;` What do you expect to happen when you say `AudioPlayer.player.start(audios);`? – k32y Feb 24 '22 at 11:34
  • 1
    Try looking at https://stackoverflow.com/questions/26305 or others for examples of how to play sounds in Java. – Stephen C Feb 24 '22 at 11:35

1 Answers1

0

It does not compile because, the type of AudioPlayer is String.

A more detailed explanation:

You are using reserve classes. See https://stackoverflow.com/a/7676877/18274209

Also see this working version (Tested in Java 11.0.2):

import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class Music {
  public static void main(String[] args) {
    playMusic("<YOUR_FILEPATH_GOES_HERE>");
  }

  public static void playMusic(String filepath) {
    try {
      AudioInputStream audioIn = AudioSystem.getAudioInputStream(
        new File(filepath)
      );
      Clip clip = AudioSystem.getClip();
      clip.open(audioIn);
      clip.start();

      Thread.sleep(10000);
    } catch (Exception ex) {
      System.out.println(ex);
    }
  }
}

See https://stackoverflow.com/a/12059638/18274209.