Page 1 of 1

Incredibly Easy Way to play Sounds Using JAVA to play MIDIs, WAVs, and AUs Rate Topic: ***-- 2 Votes

#1 WolfCoder  Icon User is offline

  • Isn't a volcano just an angry hill?
  • member icon


Reputation: 784
  • View blog
  • Posts: 7,613
  • Joined: 05-May 05

Post icon  Posted 07 January 2006 - 05:36 PM

Do you want to add sound to your JAVA application? It's so incredibly easy! You'll usually use a sound player for video game Applets but you can use it for other things too. The class that plays these sounds is called an AudioClip. It's accepts .wav, .mid, and .au files as sounds.

Consider the following code for an Applet:

import java.applet.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
public class Audioapp extends JApplet
{
	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){} // 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("song.mid");
  testsong.playSound();
	}
}



An AudioClip is an Applet thing, so you need to "import java.applet.*". The part of the code you should focus on is the Sound class:

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){} // Satisfy the catch
	}
	public void playSound()
	{
  song.loop(); // Play 
	}
	public void stopSound()
	{
  song.stop(); // Stop
	}
	public void playSoundOnce()
	{
  song.play(); // Play only once
	}
}



It has an AudioClip and a URL class. The URL is needed to locate the file in question. Next:

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



The getCodeBase gets the path of whever the JAVA code class is. The URL constructor simply gets that URL and adds the filename to your sound file at the end. Then

song = Applet.newAudioClip(songPath); // Load the Sound



Creates the new AudioClip so you can play sounds. The rest of the class is just three simple methods:

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



These are quite self-explaining. playSound loops the sound, stopSound stops the sound, and playSoundOnce is good for sound effects because it only plays the file once.

That's it! LOL! Yes, that's right, that's all you need to play sound files! In some other languages, the tutorials stretch on for pages but this one is really short! I can't belive how simple it was to do all of this! It even handles all the sound-based problems!

You don't need to make several Sound objects of the same sound to have them play at the same time, you can just call one Sound object's playSoundOnce method several times! It plays them all together! MIDIs are no problem, just load a MIDI and call playSound! And when the music should stop, call stopSound!

Just put the object in the JAVA applications in which you want to have sound played in!

Is This A Good Question/Topic? 3
  • +

Replies To: Incredibly Easy Way to play Sounds

#2 nano_daemon  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 21-September 09

Posted 21 September 2009 - 10:10 AM

Hey! A great example and very well explained. However I get a problem, the program builds fine, it's just when it runs I get this error:
-----------------------------------------------
java.lang.NoSuchMethodError: main
Exception in thread "main"
Process completed.
-----------------------------------------------
I even copy-pasted your code and i get the same error, am i making a noob mistake? please help!
Was This Post Helpful? 0
  • +
  • -

#3 nano_daemon  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 21-September 09

Posted 22 September 2009 - 12:21 AM

View Postnano_daemon, on 21 Sep, 2009 - 09:10 AM, said:

Hey! A great example and very well explained. However I get a problem, the program builds fine, it's just when it runs I get this error:
-----------------------------------------------
java.lang.NoSuchMethodError: main
Exception in thread "main"
Process completed.
-----------------------------------------------
I even copy-pasted your code and i get the same error, am i making a noob mistake? please help!

nevermind i was trying to play an mp3 file...*facepalm*
Was This Post Helpful? 0
  • +
  • -

#4 sgware  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 1
  • Joined: 17-January 10

Posted 17 January 2010 - 11:38 PM

There is an alternative to importing the sound files which works in both applets and applications: convert the audio files into .java files and simply use them in your code.

I have developed a tool which makes this process a lot easier. It simplifies the Java Sound API quite a bit.

http://stephengware....s/soundtoclass/

Hope this helps.
-- Stephen
Was This Post Helpful? 2
  • +
  • -

#5 sdhilipan89  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 22-March 10

Posted 22 March 2010 - 06:14 AM

View Postnano_daemon, on 21 September 2009 - 09:10 AM, said:

Hey! A great example and very well explained. However I get a problem, the program builds fine, it's just when it runs I get this error:
-----------------------------------------------
java.lang.NoSuchMethodError: main
Exception in thread "main"
Process completed.
-----------------------------------------------
I even copy-pasted your code and i get the same error, am i making a noob mistake? please help!

hi friend u need to have a main function either in the same class or some other new class and call this existing class members

View PostWolfCoder, on 07 January 2006 - 04:36 PM, said:

Do you want to add sound to your JAVA application? It's so incredibly easy! You'll usually use a sound player for video game Applets but you can use it for other things too. The class that plays these sounds is called an AudioClip. It's accepts .wav, .mid, and .au files as sounds.

Consider the following code for an Applet:

import java.applet.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
public class Audioapp extends JApplet
{
	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){} // 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("song.mid");
  testsong.playSound();
	}
}



An AudioClip is an Applet thing, so you need to "import java.applet.*". The part of the code you should focus on is the Sound class:

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){} // Satisfy the catch
	}
	public void playSound()
	{
  song.loop(); // Play 
	}
	public void stopSound()
	{
  song.stop(); // Stop
	}
	public void playSoundOnce()
	{
  song.play(); // Play only once
	}
}



It has an AudioClip and a URL class. The URL is needed to locate the file in question. Next:

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



The getCodeBase gets the path of whever the JAVA code class is. The URL constructor simply gets that URL and adds the filename to your sound file at the end. Then

song = Applet.newAudioClip(songPath); // Load the Sound



Creates the new AudioClip so you can play sounds. The rest of the class is just three simple methods:

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



These are quite self-explaining. playSound loops the sound, stopSound stops the sound, and playSoundOnce is good for sound effects because it only plays the file once.

That's it! LOL! Yes, that's right, that's all you need to play sound files! In some other languages, the tutorials stretch on for pages but this one is really short! I can't belive how simple it was to do all of this! It even handles all the sound-based problems!

You don't need to make several Sound objects of the same sound to have them play at the same time, you can just call one Sound object's playSoundOnce method several times! It plays them all together! MIDIs are no problem, just load a MIDI and call playSound! And when the music should stop, call stopSound!

Just put the object in the JAVA applications in which you want to have sound played in!




hi friend,
i did the same,but i get some runtime errors. i hav changed the name of the soundfile to the one i am having.Yet no output.pls help me

"Exception in thread "main" java.lang.NullPointerException
Was This Post Helpful? 0
  • +
  • -

#6 blixna_waka  Icon User is offline

  • D.I.C Head

Reputation: -5
  • View blog
  • Posts: 60
  • Joined: 14-July 10

Posted 15 July 2010 - 08:47 AM

View Postsdhilipan89, on 22 March 2010 - 12:14 PM, said:

View Postnano_daemon, on 21 September 2009 - 09:10 AM, said:

Hey! A great example and very well explained. However I get a problem, the program builds fine, it's just when it runs I get this error:
-----------------------------------------------
java.lang.NoSuchMethodError: main
Exception in thread "main"
Process completed.
-----------------------------------------------
I even copy-pasted your code and i get the same error, am i making a noob mistake? please help!

hi friend u need to have a main function either in the same class or some other new class and call this existing class members

View PostWolfCoder, on 07 January 2006 - 04:36 PM, said:

Do you want to add sound to your JAVA application? It's so incredibly easy! You'll usually use a sound player for video game Applets but you can use it for other things too. The class that plays these sounds is called an AudioClip. It's accepts .wav, .mid, and .au files as sounds.

Consider the following code for an Applet:

import java.applet.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
public class Audioapp extends JApplet
{
	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){} // 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("song.mid");
  testsong.playSound();
	}
}



An AudioClip is an Applet thing, so you need to "import java.applet.*". The part of the code you should focus on is the Sound class:

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){} // Satisfy the catch
	}
	public void playSound()
	{
  song.loop(); // Play 
	}
	public void stopSound()
	{
  song.stop(); // Stop
	}
	public void playSoundOnce()
	{
  song.play(); // Play only once
	}
}



It has an AudioClip and a URL class. The URL is needed to locate the file in question. Next:

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



The getCodeBase gets the path of whever the JAVA code class is. The URL constructor simply gets that URL and adds the filename to your sound file at the end. Then

song = Applet.newAudioClip(songPath); // Load the Sound



Creates the new AudioClip so you can play sounds. The rest of the class is just three simple methods:

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



These are quite self-explaining. playSound loops the sound, stopSound stops the sound, and playSoundOnce is good for sound effects because it only plays the file once.

That's it! LOL! Yes, that's right, that's all you need to play sound files! In some other languages, the tutorials stretch on for pages but this one is really short! I can't belive how simple it was to do all of this! It even handles all the sound-based problems!

You don't need to make several Sound objects of the same sound to have them play at the same time, you can just call one Sound object's playSoundOnce method several times! It plays them all together! MIDIs are no problem, just load a MIDI and call playSound! And when the music should stop, call stopSound!

Just put the object in the JAVA applications in which you want to have sound played in!




hi friend,
i did the same,but i get some runtime errors. i hav changed the name of the soundfile to the one i am having.Yet no output.pls help me

"Exception in thread "main" java.lang.NullPointerException


A Null Pointer Exception is when you have declared a reference to an object, but the object is not linked to it.
Dog mydog;

You likely only need to link the two.
Dog mydog = new Dog();

or
Dog mydog;
mydog = new Dog();


I hope this aids you in finding your error source.
Was This Post Helpful? 2
  • +
  • -

#7 yuihjk98  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 21-December 11

Posted 21 December 2011 - 07:42 PM

View PostWolfCoder, on 07 January 2006 - 05:36 PM, said:

Just put the object in the JAVA applications in which you want to have sound played in!


Thanks so much! This was really helpful, but how do I link it to a class so the music plays when the .jar runs?
Was This Post Helpful? 0
  • +
  • -

#8 Ruwuski  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 27-December 11

Posted 27 December 2011 - 05:29 PM

Is there an easy way to do this without the extends JApplet.

It only shows the JApplet anymore and no longer my own application.
Was This Post Helpful? 0
  • +
  • -

#9 htc(hot-taco-cheese)  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 71
  • Joined: 04-December 10

Posted 01 January 2012 - 05:17 PM

Thanks! Great write up
Was This Post Helpful? 0
  • +
  • -

#10 harrypotter2  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 24
  • Joined: 19-February 12

Posted 14 June 2012 - 11:13 AM

Hey do u guys know how to make sound in the same java application like i am trying to here:


package snake;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.util.LinkedList;
import java.util.Random;
import javax.swing.JFrame;

public class Snake extends JFrame implements KeyListener {
	private int windowWidth = 1000;
	private int windowHeight = 600;
	private LinkedList<Point> snake;
	private int dx;
	private int dy;
	private Random generator = new Random();
	private Point food;
	private int points;

	public static void main(String[] args) {
		new Snake();
	}

	public Snake() {
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setSize(windowWidth, windowHeight);
		this.setResizable(false);
		this.setLocation(10, 100);
		this.setVisible(true);

		this.createBufferStrategy(2);

		this.addKeyListener(this);

		initGame();

		while (true) {
			long start = System.currentTimeMillis();
			gameLoop();
			while (System.currentTimeMillis() - start < 40) {
			}
		}
	}

	private void initGame() {
		snake = new LinkedList<Point>();
		snake.addFirst(new Point(20, 20));
		growSnake(5);

		dx = 0;
		dy = 0;

		food = new Point(10, 10);

		points = 0;
	}

	private void gameLoop() {
		moveSnake(dx, dy);
		if (snake.getFirst().equals(food)) {
			moveFood();
			growSnake(3);
			points++;
		}
		if (snake.getFirst().x <= 0 || snake.getFirst().x >= windowWidth / 10
				|| snake.getFirst().y <= 2
				|| snake.getFirst().y >= windowHeight / 10) {
			initGame();
		}
		for (int n = 1; n < snake.size(); n++) {
			if (snake.getFirst().equals(snake.get(n))) {
				initGame();
			}
		}
		drawFrame();
	}

	private void drawFrame() {
		BufferStrategy bf = this.getBufferStrategy();
		Graphics g = null;

		try {
			g = bf.getDrawGraphics();
			g.setColor(Color.RED);
			g.fillRect(0, 0, windowWidth, windowHeight);

			drawSnake(g);
			drawFood(g);
			drawPoints(g);
		} finally {
			g.dispose();
		}
		bf.show();
	}

	private void drawSnake(Graphics g) {
		for (int n = 0; n < snake.size(); n++) {
			g.setColor(Color.GREEN);
			Point p = snake.get(n);
			g.fillOval(p.x * 10, p.y * 10, 10, 10);
		}
	}

	private void moveSnake(int dx, int dy) {
		for (int n = snake.size() - 1; n >= 1; n--) {
			snake.get(n).setLocation(snake.get(n - 1));
		}
		snake.getFirst().x += dx;
		snake.getFirst().y += dy;
	}

	private void growSnake(int n) {
		while (n > 0) {
			snake.add(new Point(snake.getLast()));
			n--;
		}
	}

	private void moveFood() {
		food.x = generator.nextInt((windowWidth / 10) - 4) + 2;
		food.y = generator.nextInt((windowHeight / 10) - 5) + 3;
	}

	private void drawFood(Graphics g) {
		g.setColor(Color.ORANGE);
		g.fillOval(food.x * 10, food.y * 10, 10, 10);
	}

	private void drawPoints(Graphics g) {
		g.setColor(Color.GRAY);
		g.drawString("points: " + points, 10, 40);
	}

	@Override
	public void keyPressed(KeyEvent e) {
		int key = e.getKeyCode();

		if (key == 37) {
			dx = -1;
			dy = 0;
		} else if (key == 38) {
			dx = 0;
			dy = -1;
		} else if (key == 39) {
			dx = 1;
			dy = 0;
		} else if (key == 40) {
			dx = 0;
			dy = 1;
		}
	}

	public void keyReleased(KeyEvent e) {
	}

	public void keyTyped(KeyEvent e) {
	}
}

Was This Post Helpful? 0
  • +
  • -

#11 Ryano121  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1362
  • View blog
  • Posts: 3,002
  • Joined: 30-January 11

Posted 14 June 2012 - 11:15 AM

Have you even read the tutorial?
Was This Post Helpful? 0
  • +
  • -

#12 harrypotter2  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 24
  • Joined: 19-February 12

Posted 14 June 2012 - 11:18 AM

View PostRyano121, on 14 June 2012 - 11:15 AM, said:

Have you even read the tutorial?



Yes, I did. But I'm not doing an applet. I just wanna insert it in the same class thats all.
Was This Post Helpful? -1
  • +
  • -

#13 Ryano121  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1362
  • View blog
  • Posts: 3,002
  • Joined: 30-January 11

Posted 14 June 2012 - 11:28 AM

The DIC search engine is pretty good -

http://www.dreaminco...3&#entry1619443

Tutorial
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1