DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Java
  4. JavaFX 2 GameTutorial Part 5

JavaFX 2 GameTutorial Part 5

Carl Dea user avatar by
Carl Dea
·
Sep. 06, 12 · Interview
Like (0)
Save
Tweet
Share
6.63K Views

Join the DZone community and get the full member experience.

Join For Free

this is part five of a six part series related to a javafx 2 game tutorial . i know it’s been a long time since i blogged about gaming, but hopefully you’re still with me. if you would like a recap, please read part 1 , part 2 , part 3 , and part 4 to find out where we left off. if you are up to date, then let’s get started!  in this blog entry we will be incorporating sounds into our game.

there are many elements which make games incredibly fun such as animated effects, collisions, ai, and input. however, one of the most important ingredients to game play is sound . when games incorporate sound effects and music, the gamer will become highly immersed (ugh… like not realizing you are about to see the sun rise). before we get into the details, let me give you some background history on sound used in pc games for the home computer. if you want to skip the history and get down to business, jump to the section called the ‘sound manager service.’ the sound manager service is responsible for maintaining sound assets used during the game. if you are really impatient and don’t care about the implementation details, jump down to ‘javafx sound demo.’ important note: remember to read the requirements before launching the demo.

history

if you want to understand today, you have to search yesterday.  ~pearl buck

back in the day, when i was growing up, i learned that the apple ][ computer was capable of playing sounds. the apple ][ had one speaker that was only able to produce simple tones (8 bit mono sound). when i first generated tones (mary had a little lamb), i was totally amazed. if you are interested in machine code using applesoft basic's peek and poke commands to compose music, visit 8 bit sound and fury .  even though 8 bits seemed very simple (because there were so few values), it was not. when creating sound effects for games, one of the most difficult things to manage was the timing or duration of the tones in conjunction with the sprites flying across the screen in a (near) simultaneous fashion. in the 90s during  the reign of the intel x86 architecture (the pc), the most popular sound card was called the sound blaster 16 made by creative technologies. in its prime, this sound card was quite amazing when playing games because it was a separate card having a chip set with the ability to play midi sounds and music in stereo (two channels). the sound card was bundled with a cd rom player allowing one to pop in a music cd. another cool feature of the sound blaster was its 15-pin midi/joystick multiport enabling game input devices to be connected. today (the future), sound cards are able to support surround sound (3d audio effects), various sound formats, record, various music formats, midi, and mixing.  multitasking enables modern computers to  play sounds/music on parallel tracks (simultaneously).

next, we will be creating a sound manager service that will be added to the game engine framework library ( jfxgen ).

sound manager service

the gameworld class contains services such as the sprite manager and (more recently) a reference to an instance of a soundmanager (singleton). the sound manager service is responsible for managing all of the game's sound effects. this service allows the developer to load sound clips ( audioclip ) using the loadsoundeffects() method. after loading sound effects each audio clip can be retrieved using a unique id (string) mapped to the sound. the last method is the shutdown() method. when the application is exited, the stop method will invoke the gameworld 's shutdown() method which, in turn, calls the soundmanager object's shutdown to clean up any resources. the soundmanager instance has a thread pool that gets gracefully shutdown.

note: for brevity, i designed the soundmanager class to play simple audio clips, though not music, during the game. if you want to add music, please refer to the javadoc on the media and mediaplayer apis.

shown below is the soundmanager class diagram:

soundmanager class diagram

figure 2: class diagram of the sound manager

the following is source code for the soundmanager class:

package carlfx.gameengine;

import javafx.scene.media.audioclip;

import java.net.url;
import java.util.hashmap;
import java.util.map;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;

/**
 * responsible for loading sound media to be played using an id or key.
 * contains all sounds for use later.
*</pre>
<pre> * user: cdea
 */
public class soundmanager {
    executorservice soundpool = executors.newfixedthreadpool(2);
    map<string, audioclip> soundeffectsmap = new hashmap<>();

    /**
     * constructor to create a simple thread pool.
     *
     * @param numberofthreads - number of threads to use media players in the map.
     */
    public soundmanager(int numberofthreads) {
        soundpool = executors.newfixedthreadpool(numberofthreads);
    }

    /**
     * load a sound into a map to later be played based on the id.
     *
     * @param id  - the identifier for a sound.
     * @param url - the url location of the media or audio resource. usually in src/main/resources directory.
     */
    public void loadsoundeffects(string id, url url) {
        audioclip sound = new audioclip(url.toexternalform());
        soundeffectsmap.put(id, sound);
    }

    /**
     * lookup a name resource to play sound based on the id.
     *
     * @param id identifier for a sound to be played.
     */
    public void playsound(final string id) {
        runnable soundplay = new runnable() {
            @override
            public void run() {
                soundeffectsmap.get(id).play();
            }
        };
        soundpool.execute(soundplay);
    }

    /**
     * stop all threads and media players.
     */
    public void shutdown() {
        soundpool.shutdown();
    }

}

how do i play sound effects in javafx?

in javafx 2, you can play small sound files efficiently with less overhead by using the audioclip api. this api allows a sound to be played repeatably. an example would be a gamer firing the weapon (left mouse press) which makes a laser sound “pew pew!” speaking of lasers in the demo game, i used a free sound file from the website freesound.org having the creative commons license. since the file was a wav file format, it was larger than it needed to be. so, i decided to convert the file to an mp3 sound format. i felt it was important to reduce the size of the file (smaller footprint) for faster loading. when converting the file to an mp3 sound format, i used sony’s sound forge software. shown below is a code snippet to play small sound files:

audioclip sound = new audioclip("laser.mp3");
sound.play();

how do i play music in javafx?

although the soundmanager (my implementation) doesn’t play music, it is easy to add the capability. the following code snippet shows how to load an mp3 file to be played using the media and mediaplayer api:

media media = new media("hymetojoy.mp3");
mediaplayer player = mediaplayerbuilder.create()
                      .media(media)
                      .onready( new runnable() {
                          @override
                          public void run() {
                             player.play();
                          })
                      .build();

javafx sound demo

requirements :

  • java 7 or later
  • javafx 2.1 or later
  • windows xp or later (should be available soon for linux/macos)

a simple asteroid type game called ‘the expanse’.

instructions:

  • right mouse click (on windows) to fly ship.
  • left mouse click (left click on windows mouse) to fire weapon.
  • key press ’2′ to change to large missiles. (blue circular projectiles)
  • other key press defaults to smaller missiles. (red circular projectiles)
  • space bar key press will toggle a force field to protect the ship from enemies and asteroids.

click on the launch button below to start the demo:

tutorial demo

part 5 ‘the expanse’ sound

references

apple ][ specs: http://apple2history.org/history/ah03/
8 bit on the apple ][: http://eightbitsoundandfury.ld8.org/programming.html
sound blaster : http://en.wikipedia.org/wiki/sound_blaster
jfxgen: https://github.com/carldea/jfxgen
javafx’s audioclip api: http://docs.oracle.com/javafx/2/api/javafx/scene/media/audioclip.html
sony sound forge: http://www.sonycreativesoftware.com/soundforgesoftware
freesound.org: http://www.freesound.org
laser sound from freesound.org: http://www.freesound.org/people/the_bizniss/sounds/39459/
creative commons license: http://creativecommons.org/licenses/sampling+/1.0/
media api: http://docs.oracle.com/javafx/2/api/javafx/scene/media/media.html
mediaplayer api: http://docs.oracle.com/javafx/2/api/javafx/scene/media/mediaplayer.html

JavaFX

Published at DZone with permission of Carl Dea. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Integration: Data, Security, Challenges, and Best Solutions
  • (Deep) Cloning Objects in JavaScript
  • 2023 Software Testing Trends: A Look Ahead at the Industry's Future
  • Cloud-Based Transportation Management System

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: