Having a Problem playing .WAV files in java - java

I was creating what I deemed to be a quite simple program that played a .wav file in Java, but the sound is not playing when the program is started. All of my imports seem to be good, and I am not too sure why it is not playing, and I am starting to wonder if it is a problem with where I placed my files. I have attached both my code, and a screenshot of the location of my files for this project here. Please tell me if more information is needed. Any help is appreciated.
package javaSounds;
import java.io.File;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class JavaSounds {
public static void main(String[] args) {
File explosion = new File("explosion.wav");
PlaySound(explosion);
}
static void PlaySound(File Sound) {
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(Sound));
clip.start();
} catch (Exception e) {
}
}
}

The problem is not the addressing but that the program finishes and closes before the sound gets played.
The command clip.start() launches and plays the sound on a daemon thread. These threads, even while running concurrently, will not hold a Java program open. Since there is nothing else happening in the program, everything shuts down and nothing is heard.
A simple way to test this is to add the command Thread.sleep(..) after starting the clip. A more usual practice is to trigger the sound from a GUI, where the presence of the GUI keeps the java program alive for the duration of the clip.
If your sound doesn't play with the addition of a sleep pause, then we can look at the addressing. By the way, it's better to get your AudioInputStream from a URL than from a File. If you plan to jar your program and include audio resources as part of the jar, File will be unable to locate those internal resources.

Related

How to get MediaPlayer to repeatedly play sound?

My MediaPlayer only plays the sound once. When I type audio.play() twice, it still only plays once. How do I get it to play again when I call audio.play()?
When I tried looking this up, most of the solutions were for Android. Where they recommended to use AudioFocus, however as my code is just Java and not Android that did not work.
I also tried to use "audio.stop()", in between the two .play()s. But that still did'nt change anything.
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import java.io.File;
public class audio {
public static void main(String[] args) {
com.sun.javafx.application.PlatformImpl.startup(()->{});
MediaPlayer audio = new MediaPlayer(
new Media(
new File("C:\\Users\\User\\Pictures\\Java Projects\\FlappyBird\\sfx_wing.mp3").toURI().toString()));
audio.play();
audio.play();
}
}
Currently, the first time I run "audio.play()", the sound correctly plays. But when I play it again, it doesn't play.
Use audio.seek(audio.getStartTime()); to play it again. Check the documentation if you have trouble understanding this line.

JavaFX - Playing an mp3

package musictesting;
import java.io.File;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.Media;
public class playsound {
public static void testsound(){
String musicFileName = "ROQUE.mp3";
Media sound = new Media(new File(musicFileName).toURI().toString());
Media song = new Media(Paths.get(musicFileName).toUri().toString());
MediaPlayer mediaPlayer = new MediaPlayer(sound);
mediaPlayer.play();
}
public static void main(String [] args){
testsound();
}
}
For a group assignment I've been deligated to make the music that plays for a game developed in Java, I've been looking at some ways to play audio files and it seems like JavaFX is the way to go. I just wanted to run like a simple test player but I get the following error:
Exception in thread "main" MediaException: MEDIA_UNAVAILABLE : C:\Users\Dylan\Documents\stuffinaround\musictesting\ROQUE.mp3 (The system cannot find the file specified)
at javafx.scene.media.Media.<init>(Unknown Source)
at musictesting.playsound.testsound(playsound.java:13)
at musictesting.playsound.main(playsound.java:19)
The file ROQUE.mp3 is in my source/bin folders.
I've tried different code people have posted online, this seems pretty straight ahead. What am I doing wrong?
Thanks in advance
Anyone having trouble with this should check out this thread, initializing JavaFX from a separate method or class fixes this, I'm not sure I understand the ins and outs yet but it works for now!
How to use JavaFX MediaPlayer correctly?

Play audio stream with JavaFX

I'm trying to make simple audio player with JavaFX Mediaplayer component. All local files are fine but i want also implement internet radio.
Code:
public static void main(String[] args) throws URISyntaxException {
new JFXPanel(); //init jfx library
String u = "http://91.121.164.186:8050";
Media m=null;
try {
m = new Media(u);
} catch (MalformedURLException e) {
e.printStackTrace();
}
MediaPlayer player = new MediaPlayer(m);
System.out.println("play");
player.play();
player.setVolume(new Double(1));
}
When I run it like this there is no errors but there is no audio. What's wrong ? What are other posibilities to play radio stream in Java ?
In your current example I can see two errors,
You are trying to run a JAVAFX component on a non-Javafx thread, which will result in error. Try running your program inside the start method. Please go through How to use JavaFX MediaPlayer correctly?
The URL you are trying to access must be a Media Compoenent
Try going through this extremely great example on Javafx Media
http://docs.oracle.com/javafx/2/media/EmbeddedMediaPlayer.zip
N.B. The example has lot more data than your require, but its a great example !
"http://91.121.164.186:8050" is a website, (HTML document), not a audio file. You need to download an audio file, something that the player knows what to do with.

On NetBeans(JAVA), Sound file suddenly stops playing when I start/test my program

First of all, this is a odd problem that im trying to fix since I got netbeans and started programming. Basically: I made a simple program with a music that should be playing while the program is running, but when the music just starts playing, it will last only some seconds because it suddenly stops playing with no apparent reason. I just open the program and click the button that makes the music to iniciate, and then it suddenly stops with 3 or 4 seconds(this is random, sometimes it ll last longer).
THE CURIOUS THING IS: On my notebook, if I try to test the program while in netbeans yet, the problem always occurs, BUT if I build the program, the problem goes away.
In other hand, if I test or build the same program on my pc(high-end), that problem will occur while testing on netbeans and after building it too, so no way to get ridding off it on pc, only on my notebook after building it(if I just test it while on netbeans without building, the problem will occur).That happens with every sound file or music that I try, also all of them are on wav format. Im not sure but I have installed K-lite mega codec pack on both systems, but dunno if its causing that. Here is part of my program where the sound file is started(and my importations):
//importations below
import java.applet.*;
import java.net.*;
import java.io.File;
import javax.swing.JOptionPane;
//my program sound stuff below
File file = new File("C:\\Users\\MY-PC\\Desktop\\Projetos\\src\\javaapplication9\\cave of the past.wav");
AudioClip clip=null;
try{
clip = Applet.newAudioClip(file.toURI().toURL());
}
catch(MalformedURLException lol){
System.err.println("LOOOOOOOOOOOOOOL");
}
clip.loop();
Never mind, I found a way that works as I want:
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("C:/Folder/musicfile.wav").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();

How to close external programs (Powerpoint) running on the native desktop using Java?

I have to create an application that will automatically open a powerpoint file, let it play through, and then close it. Not only do I need to figure out HOW to close it, but I also must detect when it closes or stops.
First option:
I know how long each powerpoint will play for, so I can hardcode when to close the file. I just need to know how to do that. There are no methods in the desktop class (that I could find) for closing.
Second option:
If someone knows a microsoft powerpoint api that lets me open powerpoints and use java to progress through the slideshow and get the state or something, that'd be great. I wouldn't have to go into each presentation and count the number of slides and the transition timer on each slide.
The opening, letting it play, and closing it is a small part of the app I need to create. But here is what I have so far with regards to THIS problem:
File myfile = new File("PowerPoint.ppsx");
try {
Desktop.getDesktop().open(myfile);
} catch (IOException ex) {
Logger.getLogger(Sc.class.getName()).log(Level.SEVERE, null, ex);
}
Probably this is the solution how to close external program:
http://www.java-forums.org/new-java/59691-close-another-program.html#post285956
If you want to detect when program has stopped running then you can start new thread with loop which from time to time will check if the program process is still running, using the same method as mentioned in link.
This is solution only for one (Windows) platform, Java is not the best choice for such tasks.
Here a solution using JNA. First we get the handle, we search using the "class name" of the window. You can determine the class name for a specific program (in this case Powerpoint) with a special utility like Spy++ (included with Visual Studio). It's possible to make the search more precise using the class name and the window caption (but here I use only the class name) so if you have more than one presentation running ... you may not close the good one!.
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinUser;
import com.sun.jna.platform.win32.WinDef.HWND;
// https://github.com/twall/jna#readme
// you need 2 jars : jna-3.5.1.jar and platform-3.5.1.jar
public class KillMyPP {
public static void main(String[] args) {
HWND hwnd = User32.INSTANCE.FindWindow("screenClass", null);
if (hwnd == null) {
System.out.println("PPSX is not running");
}
else {
User32.INSTANCE.PostMessage(hwnd, WinUser.WM_QUIT, null, null);
}
}
}

Categories