Adding sound to game application
Can anyone assist me or provide a link as to how I can add sound to an application(non-applet)? In this case it is a space invaders clone tutorial; now I would like to add sound to when either the player or the aliens fire a laser. The problem is that I'm not sure how to do it. I initially tried using the AudioStream attribute from the sun.audio class but it did not work. Also I would like to add new images to the game background but when I add images to the panel, it does not appear when executed; the game loop I think affects this. Here is some code snippets:
The initial setup function:
public Game() {
//ImagePanel p1 = new ImagePanel(new ImageIcon("City.png").getImage());
// create a frame to contain our game
JFrame container = new JFrame("Space Invaders 101");
// get hold the content of the frame and set up the resolution of the game
JPanel panel = (JPanel) container.getContentPane();
panel.setPreferredSize(new Dimension(800,600));
panel.setLayout(null);
// setup our canvas size and put it into the content of the frame
setBounds(0,0,800,600);
panel.add(this);
// Tell AWT not to bother repainting our canvas since we're
// going to do that our self in accelerated mode
setIgnoreRepaint(true);
// finally make the window visible
container.pack();
container.setResizable(false);
container.setVisible(true);
// add a listener to respond to the user closing the window. If they
// do we'd like to exit the game
container.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
// add a key input system (defined below) to our canvas
// so we can respond to key pressed
addKeyListener(new KeyInputHandler());
// request the focus so key events come to us
requestFocus();
// create the buffering strategy which will allow AWT
// to manage our accelerated graphics
createBufferStrategy(2);
strategy = getBufferStrategy();
// initialise the entities in our game so there's something
// to see at startup
initEntities();
}then the class for firing a shot:
public class ShotEntity extends Entity {
/** The vertical speed at which the players shot moves */
private double moveSpeed = -300;
/** The game in which this entity exists */
private Game game;
/** True if this shot has been "used", i.e. its hit something */
private boolean used = false;
* Create a new shot from the player
* @param game The game in which the shot has been created
* @param sprite The sprite representing this shot
* @param x The initial x location of the shot
* @param y The initial y location of the shot
public ShotEntity(Game game,String sprite,int x,int y) {
super(sprite,x,y);
this.game = game;
dy = moveSpeed;
* Request that this shot moved based on time elapsed
* @param delta The time that has elapsed since last move
public void move(long delta) {
// proceed with normal move
super.move(delta);
// if we shot off the screen, remove ourselfs
if (y < -100) {
game.removeEntity(this);
* Notification that this shot has collided with another
* entity
* @parma other The other entity with which we've collided
public void collidedWith(Entity other) {
// prevents double kills, if we've already hit something,
// don't collide
if (used) {
return;
// if we've hit an alien, kill it!
if (other instanceof AlienEntity) {
// remove the affected entities
game.removeEntity(this);
game.removeEntity(other);
// notify the game that the alien has been killed
game.notifyAlienKilled();
used = true;
}The main game loop:
public void gameLoop() {
long lastLoopTime = System.currentTimeMillis();
// keep looping round til the game ends
while (gameRunning) {
// work out how long its been since the last update, this
// will be used to calculate how far the entities should
// move this loop
long delta = System.currentTimeMillis() - lastLoopTime;
lastLoopTime = System.currentTimeMillis();
// Get hold of a graphics context for the accelerated
// surface and blank it out
Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0,0,800,600);
// cycle round asking each entity to move itself
if (!waitingForKeyPress) {
for (int i=0;i<entities.size();i++) {
Entity entity = (Entity) entities.get(i);
entity.move(delta);
// cycle round drawing all the entities we have in the game
for (int i=0;i<entities.size();i++) {
Entity entity = (Entity) entities.get(i);
entity.draw(g);
// brute force collisions, compare every entity against
// every other entity. If any of them collide notify
// both entities that the collision has occured
for (int p=0;p<entities.size();p++) {
for (int s=p+1;s<entities.size();s++) {
Entity me = (Entity) entities.get(p);
Entity him = (Entity) entities.get(s);
if (me.collidesWith(him)) {
me.collidedWith(him);
him.collidedWith(me);
// remove any entity that has been marked for clear up
entities.removeAll(removeList);
removeList.clear();
// if a game event has indicated that game logic should
// be resolved, cycle round every entity requesting that
// their personal logic should be considered.
if (logicRequiredThisLoop) {
for (int i=0;i<entities.size();i++) {
Entity entity = (Entity) entities.get(i);
entity.doLogic();
logicRequiredThisLoop = false;
// if we're waiting for an "any key" press then draw the
// current message
if (waitingForKeyPress) {
g.setColor(Color.white);
g.drawString(message,(800-g.getFontMetrics().stringWidth(message))/2,250);
g.drawString("Press any key",(800-g.getFontMetrics().stringWidth("Press any key"))/2,300);
// finally, we've completed drawing so clear up the graphics
// and flip the buffer over
g.dispose();
strategy.show();
// resolve the movement of the ship. First assume the ship
// isn't moving. If either cursor key is pressed then
// update the movement appropraitely
ship.setHorizontalMovement(0);
if ((leftPressed) && (!rightPressed)) {
ship.setHorizontalMovement(-moveSpeed);
} else if ((rightPressed) && (!leftPressed)) {
ship.setHorizontalMovement(moveSpeed);
// if we're pressing fire, attempt to fire
if (firePressed) {
tryToFire();
// finally pause for a bit. Note: this should run us at about
// 100 fps but on windows this might vary each loop due to
// a bad implementation of timer
try { Thread.sleep(10); } catch (Exception e) {}
for basic sounds, you can use the JavaSound API.
http://java.sun.com/docs/books/tutorial/sound/index.html
There are plugin libraries available that add MP3 and OGG support to it.
http://www.javazoom.net/index.shtml
Similar Messages
-
i am not able to hear any sounds of games on the speaker. Though the sounds function on the head fones. The speaker works perfect in other applications except games.Have checked all the settings but not able to fix it.
Have you got notifications muted ? Only notifications (including games) get muted, so the iPod and Videos apps, and headphones, still get sound. Depending on what you've got Settings > General > Use Side Switch To set to (mute or rotation lock), then you can mute notifications by the switch on the right hand side of the iPad, or via the taskbar : double-click the home button; slide from the left; and its the icon; press home again to exit the taskbar. The function that isn't on the side switch is set via the taskbar instead : http://support.apple.com/kb/HT4085
If that doesn't solve it then try a reset : press and hold both the sleep and home buttons for about 10 to 15 seconds (ignore the red slider), after which the Apple logo should appear - you won't lose any content, it's the iPad equivalent of a reboot. -
Recently, I can't get any sound from my game applications. Sound works fine with video, streaming, etc, but not my game applications. I've tried powering down and re-booting, but the sound does not return. Can anyone help me?
Have you got notifications muted ? Only notifications (including games) get muted, so the Music and Videos apps, and headphones, still get sound.
Depending on what you've got Settings > General > Use Side Switch To set to (mute or rotation lock), then you can mute notifications by the switch on the right hand side of the iPad above the volume switch, or via control centre : swipe up from the bottom edge of the screen and it's the right-most of the 5 icons in the middle of it (if the icon is white then it's 'on', tap it to turn it grey and 'off'). The function that isn't on the side switch is set via control centre instead : http://support.apple.com/kb/HT4085 -
My iPad will not play sounds on certain applications. ie: if I click on a video from FB sound will not play. If I go to YouTube and play the same video sound will play. Also certain games will no longer play sounds. They always played sounds but now won't now. I just went to my churches web site to watch live service and again no sound. I grabbed my dads iPad and the sound works fine.
If you lose sounds for keyboard clicks, games or other apps, email notifications and other notifications, system sounds may have been muted.
System sounds can be muted and controlled two different ways. The screen lock rotation can be controlled in the same manner as well.
Settings>General>Use Side Switch to: Mute System sounds. If this option is selected, the switch on the side of the iPad above the volume rocker will mute system sounds.
If you choose Lock Screen Rotation, then the switch locks the screen. If the screen is locked, you will see a lock icon in the upper right corner next to the battery indicator gauge.
If you have the side switch set to lock screen rotation then the system sound control is in the task bar. Double tap the home button and in the task bar at the bottom, swipe all the way to the right. The speaker icon is all the way to the left. Tap on it and system sounds will return.
If you have the side switch set to mute system sounds, then the screen lock rotation can be accessed via the task bar in the same manner as described above.
This support article from Apple explains how the side switch works.
http://support.apple.com/kb/HT4085 -
I have just added sound fonts in my library bank, but everytime i try to load a sound tru DLS my logic crashes... Plz help.
cassykeysHave you tried importing them into the EXS 24 ? Assuming the process is the same if you're on Logic X, its just a matter of putting the soundfont files into the ~/Library/Application Support/Logic/Sampler Instruments folder and the EXS converts them when you try to load them - its explained properly in the Software Instruments manual (EXS24 section), but its very quick and easy. It might provide a decent alternative.
-
How To Upload Picture And adding sound
Hi all...
Anyone if you know how to upload picture in java application and adding sound plz try to help me thx..
I need the coding for this 2 for my java application urgently//!!! I am currently using JFrame as my GUI.Eh
Upload a picture, to what? Your PDA, an FTP server, what?
and adding sound to the picture? or just to the application? Do you want a simple "Beep", or more?
I need the coding for this 2 for my java application urgently
Thats nice, I can take it then you have read the [url http://java.sun.com/docs/books/tutorial/index.html]tutorials, search google and the forums, and then posted here? It would be much faster.
I am currently using JFrame as my GUI
Good for you. -
Hi all welcome as you can see I'm new to your forum. So I have a problem as it concerns the sound in games.
Namely, I bought a Creative Headset HS-800 Fatality everything good in listening to music, etc.
But when I go to the game, I turned the sound (someone shoots to the left I hear him right, and vice versa.)
Yes, in all games but mostly it is felt such a battlefiel or call of duty.
At first I thought that this is the fault of my sound card but it's not because I was in a mate and in him was the same ... This recently replaced the computer and the same thing.
I came across the net to reverse the channels, but unfortunately I do not know how to set it up.
Here, the data on my computer:
Sound Card Speakers (Realtek High Definitie
Sound Card Realtek Digital Output (Realtek
Sound Card Realtek Digital Output (RCA) (Re
Operating system: Windows 7 64 bit
I would add that in tests Realtek win7 and everything is fine.
Regards and please help as soon as possible.Do you get any problems with sound in other (older) games? You didn't mention which drivers in particular you updated, but make sure the graphics card's ones are included.
With regards to Half Life 2, check out this page on the Steam site:
http://steampowered.custhelp.com/cgi...wYWdlPTE*&p_li=
If that page doesn't open correctly for you, just go to http://www.steampowered.com , then Support, and select Half Life 2 in the product list. It should be one of the first cases listed.
Cat -
We just moved from the United States to Costa Rica. The first two days my mac worked great. Then all of a sudden I was trying to use a game application and the screen went black and there is a white cursor which I can move around, but I can't escape it. When I restart it seems okay and I see my main screen, but only for a second and then it goes black again.
This computer was brand new in June. Is it the humidity??? What can I do. Please help!!!!No guarantess but try smc and pram resets,
-
How to change the cursor type when a TableView class was added to a Swing application?
We can resize column width by dragging the column divider in the table header. This is a built-in feature of the TableView class.
Normally, the cursor will become to east-resize (or west-resize) type with positioning the cursor just to the right of a column header.
However, I found that the cursor is remaining the default type at the same position if I integrate JavaFX into Swing Application. That is adding the TableView to a Scene, and then adding this Scene to a JFXPanel, finally, adding this JFXPanel to the JFrame.
The sample codes are listing below:
public class Run extends JFrame {
Run() {
setSize(600, 450);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
private void initComponents() {
final JFXPanel fxPanel = new JFXPanel();
this.getContentPane().add(fxPanel);
Platform.runLater(new Runnable() {
@Override
public void run() {
initFX(fxPanel);
private void initFX(JFXPanel fxPanel) {
Scene scene = null;
try {
scene = FXMLLoader.load(
new File("res/fxml_example.fxml").toURI().toURL()
} catch (Exception ex) {
ex.printStackTrace();
fxPanel.setScene(scene);
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Run().setVisible(true);
fxml_example.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.Scene?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TableColumn?>
<Scene xmlns:fx="http://javafx.com/fxml">
<TableView fx:id="tableView"
editable="true">
<columns>
<TableColumn text="COL1">
</TableColumn>
<TableColumn text="COL2">
</TableColumn>
<TableColumn text="COL3">
</TableColumn>
<TableColumn text="COL4">
</TableColumn>
<TableColumn text="COL5">
</TableColumn>
</columns>
</TableView>
</Scene>
So, are there anyone can advise how to fix these codes; make the cursor can change to east-resize (or west-resize) type when this TableView class was added to a Swing application?Thanks for the report. I've just filed a JIRA issue: https://javafx-jira.kenai.com/browse/RT-34009
//Anton. -
I have a pdf file with the added sounds, so I can not run the sound in adobe reader XI on my tablet samsung galaxi pro (android)
Thanks for writing to us. Unfortunately, such advanced javascript support is currently not provided by Adobe Reader for Android.
Thanks,
Adobe Reader Team -
How to Load Sound In Java Application?
Hi, i dunno what the codes to load sound in java application, can anyone help me and provide me with the codes? Thanks a lot.
http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=%2Btitle%3Aapplication+%2Btitle%3Asound&col=javaforums
BTW: You can doo this yourself -
Playing sound from multiple applications?
Hi, I recently started using Arch and I'm loving it but I have one problem. My ALSA can only play sound from one application at a time, so I have to use pulseaudio for the others. But pulseaudio doesn't recognize my mic so I can't remove ALSA. ALSA just says "device busy" or something. And yes I tried to search before posting but didn't find an answer.
ThanksThis is what I found from the logs:
Jul 18 21:38:34 arch pulseaudio[946]: alsa-sink.c: ALSA woke us up to write new data to the device, but there was actually nothing to write!
Jul 18 21:38:34 arch pulseaudio[946]: alsa-sink.c: Most likely this is a bug in the ALSA driver 'snd_hda_intel'. Please report this issue to the ALSA developers.
Jul 18 21:38:34 arch pulseaudio[946]: alsa-sink.c: We were woken up with POLLOUT set -- however a subsequent snd_pcm_avail() returned 0 or another value < min_avail.
Jul 19 00:53:54 arch pulseaudio[946]: alsa-sink.c: Error opening PCM device front:0: Device or resource busy
Jul 19 00:53:54 arch pulseaudio[946]: alsa-sink.c: Error opening PCM device front:0: Device or resource busy
Jul 19 21:59:22 arch pulseaudio[963]: alsa-sink.c: ALSA woke us up to write new data to the device, but there was actually nothing to write!
Jul 19 21:59:22 arch pulseaudio[963]: alsa-sink.c: Most likely this is a bug in the ALSA driver 'snd_hda_intel'. Please report this issue to the ALSA developers.
Jul 19 21:59:22 arch pulseaudio[963]: alsa-sink.c: We were woken up with POLLOUT set -- however a subsequent snd_pcm_avail() returned 0 or another value < min_avail.
Jul 20 02:35:47 arch pulseaudio[963]: alsa-sink.c: Error opening PCM device front:0: Device or resource busy
Jul 20 02:35:47 arch pulseaudio[963]: alsa-sink.c: Error opening PCM device front:0: Device or resource busy
Jul 20 12:22:05 arch pulseaudio[981]: alsa-sink.c: Error opening PCM device front:0: Device or resource busy
Jul 20 12:22:05 arch pulseaudio[981]: alsa-sink.c: Error opening PCM device front:0: Device or resource busy
Jul 20 12:22:05 arch pulseaudio[981]: alsa-sink.c: Error opening PCM device front:0: Device or resource busy
Jul 21 01:25:49 arch pulseaudio[953]: alsa-sink.c: ALSA woke us up to write new data to the device, but there was actually nothing to write!
Jul 21 01:25:49 arch pulseaudio[953]: alsa-sink.c: Most likely this is a bug in the ALSA driver 'snd_hda_intel'. Please report this issue to the ALSA developers.
Jul 21 01:25:49 arch pulseaudio[953]: alsa-sink.c: We were woken up with POLLOUT set -- however a subsequent snd_pcm_avail() returned 0 or another value < min_avail.
Jul 21 14:33:44 arch pulseaudio[973]: alsa-sink.c: Error opening PCM device front:0: Device or resource busy
Jul 21 14:33:44 arch pulseaudio[973]: alsa-sink.c: Error opening PCM device front:0: Device or resource busy
Jul 21 14:33:44 arch pulseaudio[973]: alsa-sink.c: Error opening PCM device front:0: Device or resource busy
Jul 22 01:58:04 arch pulseaudio[973]: alsa-sink.c: Error opening PCM device front:0: Device or resource busy
Jul 22 01:58:04 arch pulseaudio[973]: alsa-sink.c: Error opening PCM device front:0: Device or resource busy
Jul 22 02:20:11 arch pulseaudio[973]: alsa-sink.c: Error opening PCM device front:0: Device or resource busy
Jul 22 02:20:11 arch pulseaudio[973]: alsa-sink.c: Error opening PCM device front:0: Device or resource busy
Jul 22 02:48:30 arch pulseaudio[973]: alsa-sink.c: Error opening PCM device front:0: Device or resource busy
Jul 23 00:21:44 arch pulseaudio[973]: alsa-sink.c: ALSA woke us up to write new data to the device, but there was actually nothing to write!
Jul 23 00:21:44 arch pulseaudio[973]: alsa-sink.c: Most likely this is a bug in the ALSA driver 'snd_hda_intel'. Please report this issue to the ALSA developers.
Jul 23 00:21:44 arch pulseaudio[973]: alsa-sink.c: We were woken up with POLLOUT set -- however a subsequent snd_pcm_avail() returned 0 or another value < min_avail.
Jul 23 11:43:46 arch pulseaudio[973]: alsa-sink.c: Error opening PCM device front:0: Device or resource busy
Jul 23 11:43:46 arch pulseaudio[973]: alsa-sink.c: Error opening PCM device front:0: Device or resource busy
Jul 23 11:43:56 arch pulseaudio[973]: alsa-sink.c: Error opening PCM device front:0: Device or resource busy
Jul 24 03:05:32 arch pulseaudio[954]: alsa-sink.c: ALSA woke us up to write new data to the device, but there was actually nothing to write!
Jul 24 03:05:32 arch pulseaudio[954]: alsa-sink.c: Most likely this is a bug in the ALSA driver 'snd_hda_intel'. Please report this issue to the ALSA developers.
Jul 24 03:05:32 arch pulseaudio[954]: alsa-sink.c: We were woken up with POLLOUT set -- however a subsequent snd_pcm_avail() returned 0 or another value < min_avail.
And yes I have gstreamer.
Last edited by nerdster (2011-07-26 00:35:45) -
I installed google chrome and added it to my applications folder and it works but my desktop still has the icon of the chrome volume/disk and when i right click it gives an option to eject but it will not delete how can I get rid of it?
Drag it to the trash icon in your dock. This is a disk image, and you need to "eject" it, to get rid of it.
-
I get no sound in Flash applications like Youtube and Zynga-Frontierville. Video is fine.
I'm not sure how related is this with the thing that happened to me but here it goes.
A while ago I couldn't have two applications that can use the audio channels at the same time. For instance, if I had a paused movie with VLC I could play a video on YouTube but with no sound. Is that your case? Or it doesn't work at all? -
Have sound on games and library but not web sites.how to fix
i have a hp omini 100. i have sound on games and start up sounds and in library but not on web sites like you tube or web md or any other vidios i come across.HELP PLEASE!!!!!!!!!!!!!!!!!!!!
This question was solved.
View Solution.Luke-bryan, welcome to the forum.
Here are some suggestions on what to check:
If you don't hear sound when playing a YouTube video, try these troubleshooting steps:
Adjust the volume on your computer and speakers.
Adjust the volume control located in the lower left corner of the YouTube video player.
Restart your browser.
Try turning up the volume for other video players (like Quicktime, Real Player, or Windows Media player).
If you still have no sound after completing the steps above, these additional tips may help:
Update your Flash Player to the latest version.
Allow third-party Flash content on your computer. Learn more by visiting Adobe’s help page.
Check any Antivirus and Firewall software to see if its blocking third-party Flash content.
Try these to see if any of them help.
Please click "KUDOS Thumbs Up" if I have helped you and click "Accept as Solution" if your problem is solved.
Signature:
HP TouchPad - 1.2 GHz; 1 GB memory; 32 GB storage; WebOS/CyanogenMod 11(Kit Kat)
HP 10 Plus; Android-Kit Kat; 1.0 GHz Allwinner A31 ARM Cortex A7 Quad Core Processor ; 2GB RAM Memory Long: 2 GB DDR3L SDRAM (1600MHz); 16GB disable eMMC 16GB v4.51
HP Omen; i7-4710QH; 8 GB memory; 256 GB San Disk SSD; Win 8.1
HP Photosmart 7520 AIO
++++++++++++++++++
**Click the Thumbs Up+ to say 'Thanks' and the 'Accept as Solution' if I have solved your problem.**
Intelligence is God given; Wisdom is the sum of our mistakes!
I am not an HP employee.
Maybe you are looking for
-
Report Painter Request - Cost Center and WBS Element
Hi Everyone, Currently, my company settles all project related expenses through to a cost center by way of an internal settlement cost element (category 21). The issue with this is that when the expense gets to the cost center, they lose all visabil
-
Can't install Snow Leopard after complete format
Hi I've got a new Macbook Pro 15 (bought in August). Problems with the Bootcamp partition led to the machine not starting up at all. Unfortunately, I didn't have a Mac OS X DVD, so in desperate need of the computer I installed Ubuntu. I have since bo
-
I have installed ios7 on my iPad 4. After installation it asked me a pass code which I have never set. After multiple attempts it is disabled. I don't have backup on my iCloud or iTunes. Is there anyone who can help to enable it or to reverse iPad to
-
HD content on the latest MacBook Pro? iPhone 3G?
I have the latest 15" MacBook Pro and wanted to know if I can rent/but HD content from the iTunes store. Will I be able to play back the content on my MacBook Pro? As for the iPhone 3G, HD content will not play, correct? Thanks!
-
Version Management for Scheduling Agreement
Hi Experts, We have activated Version Management for Scheduling Agreement - LP. When we create a Scheduling Agreement, it is generating zero version but 'Net Order Value' is showing as zero in versions tab. We have also addressed fields 'NETPR' and '