1

I would like to play spacemusic.au in my applet. The music file is located in both Game/src and Game/bin. However, it does not play the music when I click "play in loop". Since it is .au file, it should be good to play. What would be causing this?

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class playMusic extends Applet 
implements ActionListener{
   Button play,stop;
   AudioClip audioClip;
   public void init(){
      play = new Button("  Play in Loop  ");
      add(play);
      play.addActionListener(this);
      stop = new Button("  Stop  ");
      add(stop);
      stop.addActionListener(this);
      audioClip = getAudioClip(getCodeBase(), "spacemusic.au");
   }
   public void actionPerformed(ActionEvent ae){
      Button source = (Button)ae.getSource();
      if (source.getLabel() == "  Play in Loop  "){
         audioClip.play();
      }  
      else if(source.getLabel() == "  Stop  "){
         audioClip.stop();
      }
   }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
jamie_y
  • 1,719
  • 2
  • 13
  • 20
  • and what is the exception on java console ? – jmj Mar 28 '14 at 17:13
  • There is no exception. It just does not play the music, as if it cannot located the file, but it's there. – jamie_y Mar 28 '14 at 17:14
  • 1) Why code an applet? If it is due to spec. by teacher, please refer them to [Why CS teachers should stop teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) Why AWT rather than Swing? See my answer on [Swing extras over AWT](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon using AWT components. – Andrew Thompson Mar 29 '14 at 06:09

3 Answers3

1

You cannot compare strings in this way

if (source.getLabel() == "  Play in Loop  "){

you should use .equals

if (source.getLabel().equals("  Play in Loop  ")){

Anyway, use a boolean variable to represent if the music is playing or not

Marco Acierno
  • 14,682
  • 8
  • 43
  • 53
1

Solved this by createding a Music folder and placed the music file in there, and referencing as "Music/spacemusic.au" See this tutorial: https://www.youtube.com/watch?v=UaNf53WflLI

jamie_y
  • 1,719
  • 2
  • 13
  • 20
0

Print the value of getCodeBase() and now you can figure it out where is the problem.

Is it pointing to a correct location or not, if yes then is spacemusic.au file present there?

Replace you actionPerformed method (use equals in place of == or use == for object reference itself)

public void actionPerformed(ActionEvent ae) {
    Button source = (Button) ae.getSource();
    if (source == play) {
        audioClip.play();
    } else if (source == stop) {
        audioClip.stop();
    }
}
Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76