简体   繁体   中英

Trying to play music in Java program

I'm trying to get a test program working that plays a sound file from my hard drive, but I continue to get NullPointerException . Here's the code so far, which I primarily ripped from dream in code :

package ForSelf;

import java.applet.*;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.ActionEvent;

import javax.swing.*;
import java.net.*;

public class AudioTest extends JApplet{
JPanel playerPanel;
JButton playSound, stopSound;
public class Sound // Holds one audio file
{
  private AudioClip song; // Sound player
  private URL songPath; // Sound path

  Sound(String filename){
     try
     {
        songPath = new URL(getCodeBase(),filename); // Get the Sound URL
        song = Applet.newAudioClip(songPath); // Load the Sound
     }catch(Exception e){
         e.printStackTrace();
         //e.getMessage();
     } // Satisfy the catch
  }

  public void playSound(){
     song.loop(); // Play 
  }
  public void stopSound(){
     song.stop(); // Stop
  }
  public void playSoundOnce(){
     song.play(); // Play only once
  }
}

public void init(){
  Sound testsong = new Sound("C:\\Users\\MyName\\Music\\PuzzleSolutionGet.wav");
  Container c = getContentPane();

  c.setBackground(Color.white);
  c.setLayout(null);

  playerPanel = new JPanel();
  playSound = new JButton("Play");
  stopSound = new JButton("Stop");

  playerPanel.add(playSound);
  playerPanel.add(stopSound);
  c.add(playerPanel);

  testsong.playSound();
}

public void paint(Graphics g){
    super.paint(g);
    playerPanel.setLocation(0, 0);
    playerPanel.setSize(300, 300);
}

public void actionPerformed(ActionEvent e){

}
}

The JComponents will be implemented later to play and stop the song file with the I'm not sure if it's just my file path or what, so any help would be appreciated.

The updated code is the following:

package ForSelf;

import java.applet.*;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.ActionEvent;

import javax.swing.*;
import java.net.*;

public class AudioTest extends JApplet{
JPanel playerPanel;
JButton playSound, stopSound;
public class Sound // Holds one audio file
{
  private AudioClip song; // Sound player
  private URL songPath; // Sound path

  Sound(String filename){
     try
     {
        songPath = new URL(getCodeBase(),filename); // Get the Sound URL
        song = Applet.newAudioClip(songPath); // Load the Sound
     }catch(Exception e){
         e.printStackTrace();
         //e.getMessage();
     } // Satisfy the catch
  }

  public void playSound(){
     song.loop(); // Play 
  }
  public void stopSound(){
     song.stop(); // Stop
  }
  public void playSoundOnce(){
     song.play(); // Play only once
  }
}

public void init(){
    **String directory = System.getProperty("user.dir") + System.getProperty("file.separator");
    String puzzleSolutionGet = directory + "PuzzleSolutionGet";
    Sound testsong = new Sound(puzzleSolutionGet);**

  //Sound testsong = new Sound("C:/Users/MyName/Music/PuzzleSolutionGet.wav");

  Container c = getContentPane();

  c.setBackground(Color.white);
  c.setLayout(null);

  playerPanel = new JPanel();
  playSound = new JButton("Play");
  stopSound = new JButton("Stop");

  playerPanel.add(playSound);
  playerPanel.add(stopSound);
  c.add(playerPanel);

  testsong.playSound();
}

public void paint(Graphics g){
    super.paint(g);
    playerPanel.setLocation(0, 0);
    playerPanel.setSize(300, 300);
}

public void actionPerformed(ActionEvent e){

}
}

I got the following exceptions when I ran it, though:

java.net.MalformedURLException: unknown protocol: c
    at java.net.URL.<init>(URL.java:574)
    at java.net.URL.<init>(URL.java:464)
    at ForSelf.AudioTest$Sound.<init>(AudioTest.java:23)
    at ForSelf.AudioTest.init(AudioTest.java:45)
    at sun.applet.AppletPanel.run(AppletPanel.java:424)
    at java.lang.Thread.run(Thread.java:662)
java.lang.NullPointerException
    at ForSelf.AudioTest$Sound.playSound(AudioTest.java:32)
    at ForSelf.AudioTest.init(AudioTest.java:62)
    at sun.applet.AppletPanel.run(AppletPanel.java:424)
    at java.lang.Thread.run(Thread.java:662)

This may prove more informative than before. I even moved the file to my desktop for faster access, but I'm certain the location isn't the issue.

You need to use forward slashes instead of backslashes. I ran your code on my linux machine using the linux path name ("/home/username/song.wav") and it did not throw any exceptions (just a warning).

I am mostly sure you need to use:

Sound testsong = new Sound("C:/Users/MyName/Music/PuzzleSolutionGet.wav");

Remember that windows accepts both forward slash and backslash as directory seperators.

If this however doesn't work for you, try using the System.getProperty("user.dir") and System.getProperty("file.separator") methods to create a String of your current directory, and then you simply need to concatenate your filename in the end:

String directory = System.getProperty("user.dir") + System.getProperty("file.separator");
String puzzleSolutionGet = directory + "PuzzleSolutionGet";
Sound testsong = new Sound(puzzleSolutionGet);

This way your code will run on any OS.

It will also save you lots of time to toggle the line where you believe the exception is thrown and try to debug the code, Stepping Into every single line until you see the exception thrown. If you haven't used the debugger, here's a cool link by IBM explaining the basics:

http://www.ibm.com/developerworks/library/os-ecbug/

Sound testsong = new Sound("C:\\Users\\MyName\\Music\\PuzzleSolutionGet.wav");
...
Sound(String filename){
     try
     {
        songPath = new URL(getCodeBase(),filename); // Get the Sound URL

The path needs to be relative to the codebase , and using forward slash / . EG if the codebase points to:

"C:\\Users\\MyName\\lib"

The constructor should look more like:

Sound testsong = new Sound("../Music/PuzzleSolutionGet.wav");

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