Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Help : I want the sound to sound at the left and right of the screen..I also want it to continue forever....but the sound plays 4 times and stop...kindly help

41 views
Skip to first unread message

Michael Adedeji

unread,
Nov 7, 2011, 6:33:32 AM11/7/11
to
import java.awt.*;
import java.util.Formatter;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.*;


import java.awt.Toolkit;



// Extends JPanel, so as to override the paintComponent() for custom
rendering codes.
public class second extends JPanel {

// Container box's width and height
private static final int BOX_WIDTH = 640;
private static final int BOX_HEIGHT = 480;
private Clip clip;
// Ball's properties
private float ballRadius = 50; // Ball's radius
private float ballX =250- ballRadius ; // Ball's center (x, y)
private float ballY = 250-ballRadius;
private float ballSpeedX = 7; // Ball's speed for x and y
//private float ballSpeedY = 2;

private static final int UPDATE_RATE = 30; // Number of refresh per
second

/** Constructor to create the UI components and init game objects. */
public second() {
super();



this.setPreferredSize(new Dimension(BOX_WIDTH, BOX_HEIGHT));


// Start the ball bouncing (in its own thread)
Thread gameThread = new Thread() {
public void run() {
try {
// Open an audio input stream.
File soundFile = new File("resources/snd16.wav");

// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
AudioInputStream audioIn =
AudioSystem.getAudioInputStream(soundFile);
clip.open(audioIn);
while (true) { // Execute one update step
// Calculate the ball's new position
ballX += ballSpeedX;
// Check if the ball moves over the bounds
// If so, adjust the position and speed.
if (ballX - ballRadius < 0) {
ballSpeedX = -ballSpeedX; // Reflect along normal
ballX = ballRadius; // Re-position the ball at the edge
clip.start();

clip.loop(Clip.LOOP_CONTINUOUSLY));



} else if (ballX + ballRadius > BOX_WIDTH) {
ballSpeedX = -ballSpeedX;
ballX = BOX_WIDTH - ballRadius;

//clip.setLoopPoints(0, 1);
clip.start();
}

// Refresh the display
repaint(); // Callback paintComponent()
// Delay for timing control and give other threads a chance
try {
Thread.sleep(1000 / UPDATE_RATE); // milliseconds
} catch (InterruptedException ex) { }
}

} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
//boolean isEnableSound;

}
};
gameThread.start(); // Callback run()
}

/** Custom rendering codes for drawing the JPanel */
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g); // Paint background

// Draw the box
g.setColor(Color.BLACK);
g.fillRect(0, 0, BOX_WIDTH, BOX_HEIGHT);

// Draw the ball
g.setColor(Color.GREEN);
g.fillOval((int) (ballX - ballRadius), (int) (ballY - ballRadius),
(int)(2 * ballRadius), (int)(2 * ballRadius));

// Display the ball's information
g.setColor(Color.WHITE);
g.setFont(new Font("Courier New", Font.PLAIN, 12));
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
formatter.format("Ball @(%3.0f) Speed=(%2.0f)", ballX,ballSpeedX);
g.drawString(sb.toString(), 20, 30);
}

/** main program (entry point) */
public static void main(String[] args) {
// Run GUI in the Event Dispatcher Thread (EDT) instead of main
thread.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Set up main window (using Swing's Jframe)
JFrame frame = new JFrame("A Moving Ball");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new second());
frame.pack();
frame.setVisible(true);
}
});
}
}

John B. Matthews

unread,
Nov 7, 2011, 12:01:44 PM11/7/11
to
In article
<bd906c49-fab3-47b0...@g1g2000vbd.googlegroups.com>,
Michael Adedeji <yank...@gmail.com> wrote:

Consider playing the Clip on another thread, as shown below. Once the
clip is initialized, it's easy to play repeatedly. A Swing Timer may be
convenient, as it's action is called on the event dispatch thread, on
which you have prudently constructed your GUI.

As an aside, watch your indents and line wrap. Also, don't try to put
the entire question in the title.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Formatter;
import javax.swing.*;
import java.io.File;
import javax.sound.sampled.*;

public class AnimationSound extends JPanel {

private static final int BOX_WIDTH = 640;
private static final int BOX_HEIGHT = 480;
private static final int RATE = 30;
private File soundFile = new File("beep.wav");
private Clip clip;
private float ballRadius = 50;
private float ballX = 250 - ballRadius;
private float ballY = 250 - ballRadius;
private float ballSpeedX = 10;

public AnimationSound() {
this.setPreferredSize(new Dimension(BOX_WIDTH, BOX_HEIGHT));
// Prepare a Clip
try {
AudioInputStream audioInputStream =
AudioSystem.getAudioInputStream(soundFile);
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info dataLineInfo =
new DataLine.Info(Clip.class, audioFormat);
clip = (Clip) AudioSystem.getLine(dataLineInfo);
clip.open(audioInputStream);
} catch (Exception e) {
e.printStackTrace(System.err);
}
Timer timer = new Timer(1000 / RATE, new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
ballX += ballSpeedX;
if (ballX - ballRadius < 0) {
ballSpeedX = -ballSpeedX;
ballX = ballRadius;
playSound();
} else if (ballX + ballRadius > BOX_WIDTH) {
ballSpeedX = -ballSpeedX;
ballX = BOX_WIDTH - ballRadius;
playSound();
}
repaint();
}
});
timer.start();
}

// Play the sound in a separate thread.
private void playSound() {
Runnable soundPlayer = new Runnable() {

@Override
public void run() {
try {
clip.setMicrosecondPosition(0);
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
}
};
new Thread(soundPlayer).start();
}

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g); // Paint background
g.setColor(Color.BLACK);
g.fillRect(0, 0, BOX_WIDTH, BOX_HEIGHT);
g.setColor(Color.GREEN);
g.fillOval(
(int) (ballX - ballRadius),
(int) (ballY - ballRadius),
(int) (2 * ballRadius), (int) (2 * ballRadius));
g.setColor(Color.WHITE);
g.setFont(new Font("Dialog", Font.PLAIN, 12));
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
formatter.format(
"Ball @(%3.0f) Speed=(%2.0f)", ballX, ballSpeedX);
g.drawString(sb.toString(), 20, 30);
}

public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
JFrame frame = new JFrame("A Moving Ball");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new AnimationSound());
frame.pack();
frame.setVisible(true);
}
});
}
}

--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>

Michael Adedeji

unread,
Nov 7, 2011, 12:27:21 PM11/7/11
to
On Nov 7, 5:01 pm, "John B. Matthews" <nos...@nospam.invalid> wrote:
> In article
> <bd906c49-fab3-47b0-ad80-82dbdcc3c...@g1g2000vbd.googlegroups.com>,
@John B. Matthews....Thanks bro...it works now. :)

Michael Adedeji

unread,
Nov 8, 2011, 8:17:44 AM11/8/11
to
What if I want the ball colours to change and also I want the size and
the speed to be like a menu?

Roedy Green

unread,
Nov 8, 2011, 9:49:43 AM11/8/11
to
Here is the code I use for making sound. Use it with a SwingTimer or
Timer to schedule future sounds.

https://wush.net/websvn/mindprod/filedetails.php?repname=mindprod&path=%2Fcom%2Fmindprod%2Fvercheck%2FPlay.java
--
Roedy Green Canadian Mind Products
http://mindprod.com
Capitalism has spurred the competition that makes CPUs faster and
faster each year, but the focus on money makes software manufacturers
do some peculiar things like deliberately leaving bugs and deficiencies
in the software so they can soak the customers for upgrades later.
Whether software is easy to use, or never loses data, when the company
has a near monopoly, is almost irrelevant to profits, and therefore
ignored. The manufacturer focuses on cheap gimicks like dancing paper
clips to dazzle naive first-time buyers. The needs of existing
experienced users are almost irrelevant. I see software rental as the
best remedy.

John B. Matthews

unread,
Nov 8, 2011, 10:08:28 AM11/8/11
to
In article
<d0ec0e85-ad00-4fe5...@w7g2000yqc.googlegroups.com>,
Michael Adedeji <yank...@gmail.com> wrote:

> What if I want the ball colours to change and also I want the size and
> the speed to be like a menu?

Just make your changes in the actionPerformed() method, before calling
repaint(). For menus, it's never too soon to learn about Action:

<http://download.oracle.com/javase/tutorial/uiswing/misc/action.html>

See also this the Model View Controller example:

<http://sites.google.com/site/drjohnbmatthews/kineticmodel>

--
[Please omit signatures when responding.]

Michael Adedeji

unread,
Nov 9, 2011, 6:48:12 AM11/9/11
to
On Nov 8, 3:08 pm, "John B. Matthews" <nos...@nospam.invalid> wrote:
> In article
> <d0ec0e85-ad00-4fe5-9a86-5511fbae1...@w7g2000yqc.googlegroups.com>,
>  Michael Adedeji <yankos...@gmail.com> wrote:
>
> > What if I want the ball colours to change and also I want the size and
> > the speed to be like a menu?
>
> Just make your changes in the actionPerformed() method, before calling
> repaint(). For menus, it's never too soon to learn about Action:
>
> <http://download.oracle.com/javase/tutorial/uiswing/misc/action.html>
>
> See also this the Model View Controller example:
>
> <http://sites.google.com/site/drjohnbmatthews/kineticmodel>
>
> --
> [Please omit signatures when responding.]
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package basics;

/**
*
* @author michaeladedeji
*/
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Formatter;
import javax.swing.*;
import java.io.File;
import javax.sound.sampled.*;

import helpers.GlobalProperties;
import java.awt.Color;
import java.util.Random;
//private Color ballColor = null;


public class AnimationSound extends JPanel {
private static final int BOX_WIDTH = 640;
private static final int BOX_HEIGHT = 480;
private static final int RATE = 30;
private File soundFile = new File("resources/snd16.wav");
private Clip clip;
private float ballRadius = 50;
private float ballX = 250 - ballRadius;
private float ballY = 250 - ballRadius;
private float ballSpeedX = 10;
private boolean randomColorMode = false;
private Color ballColor = null, numberColor = null;
private Color backgroundColor;

public AnimationSound() {
this.setPreferredSize(new Dimension(BOX_WIDTH, BOX_HEIGHT));
// Prepare a Clip

try {
AudioInputStream audioInputStream =
AudioSystem.getAudioInputStream(soundFile);
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info dataLineInfo =
new DataLine.Info(Clip.class, audioFormat);
clip = (Clip) AudioSystem.getLine(dataLineInfo);
clip.open(audioInputStream);
} catch (Exception e) {
e.printStackTrace(System.err);
}
Timer timer = new Timer(1000 / RATE, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ballX += ballSpeedX;
if (ballX - ballRadius < 0) {
ballSpeedX = -ballSpeedX;
ballX = ballRadius;
playSound();
//getParameters();
} else if (ballX + ballRadius > BOX_WIDTH) {
ballSpeedX = -ballSpeedX;
ballX = BOX_WIDTH - ballRadius;
playSound();
//getParameters();
}
repaint();

}
});
timer.start();
}
// Play the sound in a separate thread.
private void playSound() {
Runnable soundPlayer = new Runnable() {
@Override
public void run() {
try {
clip.setMicrosecondPosition(0);
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
}
};
new Thread(soundPlayer).start();
}
private void getColors() {
if(randomColorMode){
Random ran = new Random();
int ranInt = ran.nextInt(4);

switch(ranInt){
case 0: ballColor = Color.white;break;
case 1: ballColor = Color.blue;break;
case 2: ballColor = Color.yellow;break;
default: ballColor = Color.red;break;
}
}


if(ballColor.equals(Color.white)){
numberColor = Color.red;
backgroundColor = Color.black;
}
else if(ballColor.equals(Color.blue)){
numberColor = Color.yellow;
backgroundColor = Color.black;
}
else if(ballColor.equals(Color.yellow)){
numberColor = Color.black;
backgroundColor = Color.black;
}
else{
numberColor = Color.white;
backgroundColor = Color.black;
}
}
private void getParameters() {

if(ballColor.equals(Color.black))
randomColorMode = true;
else
randomColorMode = false;

getColors();
}

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g); // Paint background

//getParameters();
g.setColor(backgroundColor);
g.fillRect(0, 0, BOX_WIDTH, BOX_HEIGHT);
g.setColor(ballColor);
//this.getParameters();
g.fillOval(
(int) (ballX - ballRadius),
(int) (ballY - ballRadius),
(int) (2 * ballRadius), (int) (2 * ballRadius));
g.setColor(ballColor);
g.setFont(new Font("Dialog", Font.PLAIN, 12));
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
formatter.format(
"Ball @(%3.0f) Speed=(%2.0f)", ballX, ballSpeedX);
g.drawString(sb.toString(), 20, 30);
}
public static void main(String[] args) {

javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override

public void run() {
JFrame frame = new JFrame("A Moving Ball");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new AnimationSound());
frame.pack();
frame.setVisible(true);
}
});
}

}

I don't know how to connect the color to make it change the ball...any
help???
0 new messages