How to make volume up down animation in Java - java

I am developing a music player and I am almost done. But I need to try something because I have seen there are more commercial music applications use different types of animations for volume up and down while playing the music.
I need something like this,
.
How can I do this? Can anybody help me? Thank you in advance.

If you are outputting your audio via a SourceDataLine, it is possible to inspect the audio data as it is being processed. There is a useful code example of this presented in the Oracle Sound Trail tutorials, on the page Using Files and Format Converters, in the section "Reading Sound Files". The important point in the code is marked with a comment "// Here, do something useful"
At that point you would convert the bytes to audio values, and use the values as part of an RMS calculation. Details for the coversion and the RMS calculation should be searchable--I know I've seen explanations for both on stackoverflow.
Once you have an RMS value calculated, it can be sent to an independent thread that handles the graphics visualization. A loose-coupling pattern should be employed so that you minimize the amount of work being done on the audio thread, and so that you avoid any blocking that might hang up the audio.
For example, the visualization thread can have a setRMSValue method that simply updates an instance variable, without synchronization or blocking of any sort. The audio processing thread can call this method freely as it generates new RMS data points. The visualizer can simultaneously read the current instance variable at your animation rate. No synchronization needed. If the visualization thread skips a few RMS data points, it should not a problem.

Related

adding sfx on Clip object in java

I'm working on a project where I will have one 24-hours long sound clip which has different phases based on local daytime (morning phase has one sound, transition phases, evening phase, etc.)
so here is what i got now, and it's ok
method that plays the clip (turns current local time in microseconds and sets starting point to match current time - if i start program 13:35 it will start playing mid-day phase of sound which is on that position, and it's ok
void playMusic(String musicLocation){
try{
File musicPath = new File(musicLocation);
if(musicPath.exists())
{
Calendar calendar = Calendar.getInstance();
//Returns current time in millis
long timeMilli2 = calendar.getTimeInMillis();
System.out.println("Time in milliseconds using Calendar: " + (timeMilli2 * 1000)) ;
AudioInputStream audioInput = AudioSystem.getAudioInputStream(musicPath);
Clip clip = AudioSystem.getClip();
clip.open(audioInput);
clip.setMicrosecondPosition(12345678);
clip.start();
clip.loop(Clip.LOOP_CONTINUOUSLY);
System.out.println(clip.getMicrosecondLength());
//setFramePosition
JOptionPane.showMessageDialog(null, "Press OK to stop playung");
}
else
{
System.out.println("no file");
}
}catch(Exception ex){
ex.printStackTrace();
}
}
main method that just calls this method
public static void main(String[] args) {
String filepath = "src/sounds/test_file.wav";
PyramidMethods pyra = new PyramidMethods();
pyra.playMusic(filepath);
}
now this is pretty simple and straightforward, and also what I need, but now what i wonder is the following -> can I and if can, how, add sound effects based on the temperature outside?
so what I was thinking is to open separate thread in main which would regularly check some wheather API and when temperature changes add sound effects like echo, distortion or something else based on temperature change (if it's colder then x it would put echo sound effect on running clip, etc.)
it this even possible in Java? it's my first time using sounds with Java so I am even inexperienced with the search terms here, would someone suggest some other programming language for it?
thanks for your answers in advance.
That must be a huge file!
Yes, Java works quite well for creating and managing soundscapes.
It is possible to play and hear different Clips at the same time. When you play them, Java automatically creates a Thread for that playback, and most operating systems will mix together all the playing threads. At one time there were Linux systems that only allowed a single output. IDK if that is still a limitation or if you are even targeting Linux systems. Also, there is going to be a ceiling on the total number of sound playbacks that an OS will be able to handle cleanly. (Usually what happens is you get dropouts if you overstress the system in this way.)
To manage the sounds, I'd consider using a util.Timer (not the Swing.Timer), and check the time and date (and weather if you have an API for that) with each iteration before deciding what to do with the constituent cues of your mix. Or maybe use an util.concurrent.ExecutorService. If your GUI is JavaFX, an AnimationTimer is also a reasonable choice.
If you do prefer to mix the sound files down to a single output line, this can most easily be done by using a library such as TinySound or AudioCue. With AudioCue (which I wrote) you can both mix down to a single output, and have guaranteed volume, panning and even playback speed management for each sound cue that is part of your "soundscape".
This could help with lowering the total amount of RAM needed to run program. As I show in a demo, one can take a single cue (e.g. a frog croak) and play it multiple times as different volumes, pans, and speeds to create the illusion of a whole pond of frogs croaking. Thus, a single .wav, only a second in length can be used to simulate a .wav that is hours in length.
I think if you want to add effects like echo or distortion, you will have to use a library or write your own. Java supports Processing Audio with Controls, but this is highly dependent upon the OS of the computer being used. Echo and Distortion are not terribly difficult to write though, and could be added to the AudioCue library code if you have incorporated that into your program. (Echo involves adding a time delay, usually using an array to hold sound data until it is time for it to play, and Distortion involves running the PCM sound data through a transform function, such as Math.tanh and a max and min to keep the results within the [-1, 1] range.)
For other possible libraries or languages, I believe both Unity (C#) and Unreal (C++) game engines/environments have extensive array of audio effects implemented, including 3D handling.

Fast Audio File Output

I've recently finished a small game and have been trying to add audio to it. Currently the sound system I have is working (basically the same code as the top answer here
), but there is a significant stall during every output (~200-300 ms). Since it's a quick game I'm looking for something significant quicker. I'm not experienced with Threads, but would those be applicable here?
Instead of reading the file every time you wish to play its contents in audio format, read the file once into a byte array and then read the audio from that array of bytes.
public static byte[] getBytes(String file) {
RandomAccessFile raf = new RandomAccessFile(file, "r");
byte[] bytes = new byte[(int) raf.length()];
raf.read(bytes);
return bytes;
}
Then, you could simply alter the playSound method to take a byte array as the parameter, and then write them to the SourceDataLine instance to play the sound (like is done in the original method, but it reads them from the file just before it writes them).
You could try passing a BufferedInputStream to the overloaded method AudioSystem.getAudioInputStream() instead of passing a File.
The call to drain is a blocking one and it causes the delays that you observe. You do not need to wait there. However, if you let the sound output operate in parallel with your other code, you should also define what happens if there is a lot of sound in your sound buffers and you are queueing more. Learn about the available method and the rest of the API to be able to manage the sound card flexibly and without any "lagging sound" effects.
Threads can also be used for this purpose, but it is not necessary here. The role of the parallel process can be adequately played by the sound driver itself and the single threaded approach will make your application easier to design and easier to debug.
As much as I'd like to accept one of these existing answers, I solved my problem in a simple way. By loading all the referenced File variables during initialization, the delay does not come back at any point during gameplay. However if this is not an adequate solution for anyone else viewing this question, I would also recommend Vulcan's answer.

Java simple Analytics/Event Stream Processing with front end

My application takes a lot of measurements of it's internal processes. For example I time certain methods, I time external webservice calls and I also have variables which have a changing value, and processes which have a 'state' (e.g. PAUSED, WAITING etc).
The application uses 100 to 200 threads, and each bit of data would be associated with a particular thread.
I am looking for some software that I can channel all this information into that would produce useful metrics and graphs of the data (ideally in real time or close to real time), let me set thresholds to trigger warnings, would allow me to filter the data by thread or thread group, etc etc.
The application is performing time critical tasks so the software/api would need to be very fast and never block.
The application is written in java, and ideally the software/api would be in java as well. I think what I'm looking for is called Event Stream Processing, but I'm really not sure what language to use to describe it.
All I've found so far are Esper and ERMA. Can anyone give me a recommendation? I'm the only one working on this project so I'm hoping for something that is pretty easy to set up and use, and has a workable front end.
In the end I found Graphite which was pretty close to being exactly what I wanted. Not the simplest to set up and configure however, but I got it working in the end.
http://graphite.wikidot.com/
In my case I send data directly from my application to Statsd (via UDP), which collects the data and does some pre processing before it ends up in the whisper back end, there is a simple example of a java interface here https://github.com/etsy/statsd/commit/2253223f3c19d2149d65ec5bc802198ff93da4cb
Alternatively you could send your data directly to graphite, example here http://neopatel.blogspot.co.uk/2011/04/logging-to-graphite-monitoring-tool.html

Synch 2 similar audio input (one by file and one by microphone)

i have 2 audio input of a concert.
The first is a wav file and the second is taken by microphone in real time.
I need play the first file in synch with the microphone input.
What library can i use?
Is there any tutorial, guide or example for do this?
thanks
Take a look here
This is entire sound api documentation
http://download.oracle.com/javase/1.5.0/docs/guide/sound/programmer_guide/
Also
Chapter 4: Synchronizing Playback on Multiple Lines
Chapter 6: Processing Audio with Controls
BUT
here is what i found in jsresource faq
How can I synchronize two or more playback lines ?
The synchronization functions in Mixer are not implemented. Nevertheless, playback typically stays in sync
How can I synchronize playback (SourceDataLines) with recording (TargetDataLines)?
As with multiple playback lines from the same Mixer object, playback and recording lines from the same Mixer object stay in sync once they are started. In practice, this means that you can achieve synchronization this easy way only by using the "Direct Audio Device" mixers. Since the "Java Sound Audio Engine" only provides playback lines, but no recording lines, playback/recording sync is not as easy with the "Java Sound Audio Engine".
If playback and recording lines originate from different Mixer objects, you need to synchronize the soundcards that are represented by the Mixer objects. So the situation is similar to external synchronization.
AND
The main problem is buffering and processing mic audio hits and timing realtime , a practical way is using external clock
And here is a bunch of java sound resources , i think u should look at monitoring sound section in api documentation and try to trigger timedelay based on hits and monitor outputs , it's little complicated i also interested in this question i will try to find out if i did i will let u know
Take a look at this links and it's going to be easy as i found and read description of this processing libraries
http://sonia.pitaru.com/
http://visualap.java.net/
http://www.softsynth.com/jsyn/ Check this out
http://jmetude.dihardja.de/
http://www.tree-axis.com/Ess/
http://www.abstract-codex.net/tactu5/index.html
http://code.google.com/p/echonestp5/

Gameloop for j2me "turn-based" game

Edit: This makes alot more sense to me now that i've taken a step away from the code, thanks for the help.
Just found stack overflow the other day through Coding Horror and it looks awesome. Figure that i'd ask the community about a problem i'm currently trying to work out.
I'm developing a roguelike sortof game using j2me for midp 2.0 phones. The project is still in the basic stages of development as I figure out how it's going to work. The part i'm currently stuck on has to do with threading.
The game has a custom HaxCanvas class which extends GameCanvas and Implements runnable. It's run method calls repaint() and then sleeps for 50 ms, resulting in a frame rate of 20 FPS. This allows me to write the rest of the game without having to put repaint everywhere and should make animations and effects easier to do later on. (at least in theory).
The flow of the game is controlled by a GameManager class, which loops through all the NPC's on the map, taking their turns, until it's the player's turn. At this point I need to get input to allow the player to move around and/or attack things. I originally was calling gameManager.runUntilHeroTurn() in the keyPressed method of my HaxCanvas. However after reading up on j2me system threads I realized that putting a method with the potential to run for a while in a callback is a bad idea. However I must used keyPressed to do input handeling, since i need access to the number keys, and getKeyStates() does not support this.
Sofar my attempts to put my gameloop in it's own thread have resulted in disaster. A strange "uncaught ArrayIndexOutOfBoundsException" with no stack trace shows up after the game has run for several turns .
So i suppose my question is this:
For a "turn based" game in j2me, what's the best way to implement the game loop, allowing for input handeling only when it's the player's turn?
Although not j2me specifically you should capture user input, the general strategy is to queue the input it until its time to process the input.
input ---> queue <---> Manager(loop)
This way you can even script input for debug purposes.
So you don't need a new thread. Each time the user presses key you store them in a buffer, and then process the contents of the buffer when necessary. If the player buffer has no input, the manager should skip all gameplay, do animations and then start over (since the game is not an action game).
I would avoid threading for the game logic as J2ME threading, depending on manufacturer of course, does not do a great job of sharing the limited resources. You will often see pauses while a thread does heavy processing. I would only recommend threads for loading or network connectivity features as in this case you will just be giving the user basic "Loading..." feedback.
To handle this, I would not have sub-loops to update each of the AI in one frame. I would do something like following in the run function:
public void run() {
while(true) {
// Update the Game
if(gameManager.isUsersTurn()) {
// Collect User Input
// Process User Input
// Update User's State
}
else {
// Update the active NPC based on their current state
gameManager.updateCurrentNPC();
}
// Do your drawing
}
}
You want to avoid having everything updated in one frame as 1) the updating might be slow, resulting in no immediate visual feedback for the user 2) you can't animate each individual NPC as they make their action. With this setup you could have NPC states, NPC_DECIDE_MOVE and NPC_ANIMATING, that would allow you further control of what the NPC is doing. NPC_ANIMATING would basically put the game in a waiting state for the animation to take place, avoiding any further processing until the animation is complete. Then it could move on to the next NPC's turn.
Also, I would just have a gameManager.update() and gameManager.paint(g) (paint would be called from paint) that would handle everything and keep the run method thin.
Finally, did you look into flushGraphics()? With the GameCanvas you usually create a Graphics object, draw everything to that and then call flushGraphics(), then wait. The method you mention is the way of tackling it for the Canvas class. Just thought I would mention this and post a link:
Game Canvas Basics

Categories

Resources