Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 33

Thread: Adding sound to program.

  1. #1
    Junior Member
    Join Date
    Dec 2011
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Adding sound to program.

    EDIT - My main class is a JFrame gui
    I have a sound class which access' a .wav in my java package. This is the PlaySound class:
    package Bluemoon;
    import java.io.*;
    import javax.sound.sampled.*;
     
    public class PlaySound
    {
    	public static void main(String[] args)
    	{
    		sound = new File("Bluemoon\\Song.wav"); // Write you own file location here and be aware that it need to be an .wav file
     
    		new Thread(play).start();
    	}
     
    	static File sound;
    	static boolean muted = false; // This should explain itself
    	static float volume = 100.0f; // This is the volume that goes from 0 to 100
    	static float pan = 0.0f; // The balance between the speakers 0 is both sides and it goes from -1 to 1
     
    	static double seconds = 0.0d; // The amount of seconds to wait before the sound starts playing
     
    	static boolean looped_forever = false; // It will keep looping forever if this is true
     
    	static int loop_times = 0; // Set the amount of extra times you want the sound to loop (you don't need to have looped_forever set to true)
    	static int loops_done = 0; // When the program is running this is counting the times the sound has looped so it knows when to stop
     
    	final static Runnable play = new Runnable() // This Thread/Runnabe is for playing the sound
            {
     
     
     
     
    		public void run()
    		{ 
    			try
    			{ 
    				// Check if the audio file is a .wav file
    				if (sound.getName().toLowerCase().contains(".wav"))
    				{
    					AudioInputStream stream = AudioSystem.getAudioInputStream(sound);
     
    					AudioFormat format = stream.getFormat();
     
    					if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED)
    					{
    						format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
    								format.getSampleRate(),
    								format.getSampleSizeInBits() * 2,
    								format.getChannels(),
    								format.getFrameSize() * 2,
    								format.getFrameRate(),
    								true);
     
    						stream = AudioSystem.getAudioInputStream(format, stream);
    					}
     
     
    					SourceDataLine.Info info = new DataLine.Info(
    							SourceDataLine.class,
    							stream.getFormat(),
    							(int) (stream.getFrameLength() * format.getFrameSize()));
     
    					SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
    					line.open(stream.getFormat());
    					line.start();
     
    					// Set Volume
    					FloatControl volume_control = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
    					volume_control.setValue((float) (Math.log(volume / 100.0f) / Math.log(10.0f) * 20.0f));
     
    					// Mute
    					BooleanControl mute_control = (BooleanControl) line.getControl(BooleanControl.Type.MUTE);
    					mute_control.setValue(muted);
     
    					FloatControl pan_control = (FloatControl) line.getControl(FloatControl.Type.PAN);
    					pan_control.setValue(pan);
     
    					long last_update = System.currentTimeMillis();
    					double since_last_update = (System.currentTimeMillis() - last_update) / 1000.0d;
     
    					// Wait the amount of seconds set before continuing
    					while (since_last_update < seconds)
    					{
    						since_last_update = (System.currentTimeMillis() - last_update) / 1000.0d;
    					}
     
    					System.out.println("Playing!");
     
    					int num_read = 0;
    					byte[] buf = new byte[line.getBufferSize()];
     
    					while ((num_read = stream.read(buf, 0, buf.length)) >= 0)
    					{
    						int offset = 0;
     
    						while (offset < num_read)
    						{
    							offset += line.write(buf, offset, num_read - offset);
    						}
    					}
     
    					line.drain();
    					line.stop();
     
    					if (looped_forever)
    					{
    						new Thread(play).start();
    					}
    					else if (loops_done < loop_times)
    					{
    						loops_done++;
    						new Thread(play).start();
    					}
    				}
     
    			}
    			catch (Exception ex) { ex.printStackTrace(); }
    		}
    	};
     
     
     
     
    }

    And i'm trying to call the run method in my main class by using :
    Playsound s = new PlaySound();
    s.run();

    Any help will be greatly appreciated. Thanks.
    Last edited by Archibold9; December 21st, 2011 at 10:22 AM.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Adding sound to program.

    Can you explain what happens or does not happen?

  3. #3
    Junior Member
    Join Date
    Dec 2011
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Adding sound to program.

    An error comes under
    s.run();
    saying cannot find symbol.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Adding sound to program.

    Please post the full text of the error message.

  5. #5
    Junior Member
    Join Date
    Dec 2011
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Adding sound to program.

    Cannot find symbol
    symbol: method run()
    location Bluemoon.PlaySound

    P.s I'm using netbeans because it has the JFrame editor.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Adding sound to program.

    Where is the run() method defined?
    I copied, compiled and executed your code with no problem.

    There is no s.run() in the code you posted???

    You should post the code you are having problems with if you want help with it.
    The posted code works fine. If you have changed it, you need to post the new code!!!

  7. #7
    Junior Member
    Join Date
    Dec 2011
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Adding sound to program.

    I'm trying to run the 'run' method in the PlaySound class in my main class called Bluemoon. The code you're asking me to paste is near 300 lines long.
    Last edited by Archibold9; December 21st, 2011 at 12:53 PM.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Adding sound to program.

    Right, don't post all of that. Make a very short test program to post.

  9. #9
    Junior Member
    Join Date
    Dec 2011
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Adding sound to program.

    PlaySound s = new PlaySound();
    private void BeginActionPerformed(java.awt.event.ActionEvent evt) {
    text1.setText("")
    Begin.setVisible(false);
    choice1.setVisible(true);
    health.setVisible(true);
    health.setText("Health = 10");
    s.run();
    }

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Adding sound to program.

    That code will not compile. If I can't compile it I can't test it.

  11. #11
    Junior Member
    Join Date
    Dec 2011
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Adding sound to program.


  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Adding sound to program.

    Where is the run() method defined?
    What class is it in?

  13. #13
    Junior Member
    Join Date
    Dec 2011
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Adding sound to program.

    The 'PlaySound' class.

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Adding sound to program.

    Are you sure run() is a method in the PlaySound class?

    If you have changed the class from your earlier posting, please post a new copy of the PlaySound class.

  15. #15
    Junior Member
    Join Date
    Dec 2011
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Adding sound to program.

    package Bluemoon;
    import java.io.*;
    import javax.sound.sampled.*;
     
    public class PlaySound
    {
    	public static void main(String[] args)
    	{
    		sound = new File("Bluemoon\\Song.wav"); // Write you own file location here and be aware that it need to be an .wav file
     
    		new Thread(play).start();
    	}
     
    	static File sound;
    	static boolean muted = false; // This should explain itself
    	static float volume = 100.0f; // This is the volume that goes from 0 to 100
    	static float pan = 0.0f; // The balance between the speakers 0 is both sides and it goes from -1 to 1
     
    	static double seconds = 0.0d; // The amount of seconds to wait before the sound starts playing
     
    	static boolean looped_forever = false; // It will keep looping forever if this is true
     
    	static int loop_times = 0; // Set the amount of extra times you want the sound to loop (you don't need to have looped_forever set to true)
    	static int loops_done = 0; // When the program is running this is counting the times the sound has looped so it knows when to stop
     
    	final static Runnable play = new Runnable() // This Thread/Runnabe is for playing the sound
            {
     
     
     
     
    		public void run()
    		{ 
    			try
    			{ 
    				// Check if the audio file is a .wav file
    				if (sound.getName().toLowerCase().contains(".wav"))
    				{
    					AudioInputStream stream = AudioSystem.getAudioInputStream(sound);
     
    					AudioFormat format = stream.getFormat();
     
    					if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED)
    					{
    						format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
    								format.getSampleRate(),
    								format.getSampleSizeInBits() * 2,
    								format.getChannels(),
    								format.getFrameSize() * 2,
    								format.getFrameRate(),
    								true);
     
    						stream = AudioSystem.getAudioInputStream(format, stream);
    					}
     
     
    					SourceDataLine.Info info = new DataLine.Info(
    							SourceDataLine.class,
    							stream.getFormat(),
    							(int) (stream.getFrameLength() * format.getFrameSize()));
     
    					SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
    					line.open(stream.getFormat());
    					line.start();
     
    					// Set Volume
    					FloatControl volume_control = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
    					volume_control.setValue((float) (Math.log(volume / 100.0f) / Math.log(10.0f) * 20.0f));
     
    					// Mute
    					BooleanControl mute_control = (BooleanControl) line.getControl(BooleanControl.Type.MUTE);
    					mute_control.setValue(muted);
     
    					FloatControl pan_control = (FloatControl) line.getControl(FloatControl.Type.PAN);
    					pan_control.setValue(pan);
     
    					long last_update = System.currentTimeMillis();
    					double since_last_update = (System.currentTimeMillis() - last_update) / 1000.0d;
     
    					// Wait the amount of seconds set before continuing
    					while (since_last_update < seconds)
    					{
    						since_last_update = (System.currentTimeMillis() - last_update) / 1000.0d;
    					}
     
    					System.out.println("Playing!");
     
    					int num_read = 0;
    					byte[] buf = new byte[line.getBufferSize()];
     
    					while ((num_read = stream.read(buf, 0, buf.length)) >= 0)
    					{
    						int offset = 0;
     
    						while (offset < num_read)
    						{
    							offset += line.write(buf, offset, num_read - offset);
    						}
    					}
     
    					line.drain();
    					line.stop();
     
    					if (looped_forever)
    					{
    						new Thread(play).start();
    					}
    					else if (loops_done < loop_times)
    					{
    						loops_done++;
    						new Thread(play).start();
    					}
    				}
     
    			}
    			catch (Exception ex) { ex.printStackTrace(); }
    		}
    	};
     
     
     
     
    }

    About half way down. The constructor.
    public void run()

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Adding sound to program.

    that is not a constructor. It's a method.
    Add this line first thing in the run method:
    System.out.println("run this="+ this);
    And look what is printed out when it executes.
    Now look in the folder containing the class files and see if there is a class file with the same name as was printed by the above.

  17. #17
    Junior Member
    Join Date
    Dec 2011
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Adding sound to program.

    Error Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: Bluemoon.PlaySound.run
    at Bluemoon.Bluemoon.BeginActionPerformed(Bluemoon.ja va:173)
    at Bluemoon.Bluemoon.access$200(Bluemoon.java:24)
    at Bluemoon.Bluemoon$3.actionPerformed(Bluemoon.java: 84)
    at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(BasicButtonListener.java:252)
    at java.awt.AWTEventMulticaster.mouseReleased(AWTEven tMulticaster.java:289)
    at java.awt.Component.processMouseEvent(Component.jav a:6504)
    at javax.swing.JComponent.processMouseEvent(JComponen t.java:3321)
    at java.awt.Component.processEvent(Component.java:626 9)
    at java.awt.Container.processEvent(Container.java:222 9)
    at java.awt.Component.dispatchEventImpl(Component.jav a:4860)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2287)
    at java.awt.Component.dispatchEvent(Component.java:46 86)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2713 )
    at java.awt.Component.dispatchEvent(Component.java:46 86)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:707)
    at java.awt.EventQueue.access$000(EventQueue.java:101 )
    at java.awt.EventQueue$3.run(EventQueue.java:666)
    at java.awt.EventQueue$3.run(EventQueue.java:664)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:680)
    at java.awt.EventQueue$4.run(EventQueue.java:678)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 677)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:211)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:128)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:117)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:113)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:105)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:90)
    -------------------------------------------------------------------------------------------------
    I checked in the src folder for my project and there was no class file with that name.

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Adding sound to program.

    The code you posted compiles and executes on my system.
    Did you try to compile and execute what was posted in post #1?

    Compile and execute the class: PlaySound that was posted in post#1.

  19. #19
    Junior Member
    Join Date
    Dec 2011
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Adding sound to program.

    So it plays sound on your system??

  20. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Adding sound to program.

    The code that you posted for the class: PlaySound compiles and executes on my system and plays a sound.

  21. #21
    Junior Member
    Join Date
    Dec 2011
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Adding sound to program.

    Yes. It works as a single class. But what i want to do is run the method public void run() in another class when you press a button.

  22. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Adding sound to program.

    Did you add the println and look at the output?

    The print out will show you what class run() is in.

  23. #23
    Junior Member
    Join Date
    Dec 2011
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Adding sound to program.

    Yes. I pasted it, man. But it told me run is in PlaySound, which it is.

  24. #24
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Adding sound to program.

    I don't think so. Post the print out here and I'll show you.

  25. #25
    Junior Member
    Join Date
    Dec 2011
    Posts
    22
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Adding sound to program.

    Yes. I pasted it, man. It told me the run() method was in PlaySound, which it is..

Page 1 of 2 12 LastLast

Similar Threads

  1. Recording Sound
    By mulligan252 in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: July 1st, 2014, 12:45 AM
  2. Adding sound to a game application
    By Shaybay92 in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: September 13th, 2011, 07:56 AM
  3. Paint program adding classes to main method class
    By Maxfmc in forum What's Wrong With My Code?
    Replies: 0
    Last Post: April 15th, 2011, 07:01 PM
  4. [SOLVED] Problem with a tutorial program(Adding the answer of two squared numbers together)
    By Melawe in forum What's Wrong With My Code?
    Replies: 20
    Last Post: April 7th, 2010, 09:03 AM
  5. need help with Timer and sound
    By amahara in forum AWT / Java Swing
    Replies: 4
    Last Post: February 18th, 2010, 12:22 PM