I want to make a program that plays sounds and displays png images onto the JFrame. I am trying to put the png and sound files (.wav) into the package that the class that's displaying it is in. I can't seem to get it working though. I've looked up many methods on how to do it, it every time they all pop up NullPointer errors. Or that it couldn't find the file, even though the file path specified was exactly where it was when I went into File Explorer. So if anyone can help me find a way to play music and display the picture (getting the png file and making it an ImageIcon), that would be great.
Here is java code
Play Button action Performed
private void play_btnActionPerformed(java.awt.event.ActionEvent evt) {
SetImage();
PlaySound();
}
Play audio
void PlaySound() {
try (InputStream in = getClass().getResourceAsStream("sam.wav")) {
InputStream bufferedInS = new BufferedInputStream(in);
try (AudioInputStream audioInS = AudioSystem.getAudioInputStream(bufferedInS)) {
Clip clip = AudioSystem.getClip();
clip.open(audioInS);
clip.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
set image
void SetImage() {
audio_icon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/player/player.png")));
}
Related
I am trying to make a game and attempting to make a "mute" and "unmute" button, but I cant figure out how to make it so when you push the button it stops the same clip that is being played at the beginning of the program. (using different methods of course).
I attempted to make the clip and audio public, but I keep getting an error and I'm not sure why.
public class TowerDefense
{
String filepath = "MenuTheme.wav";
private Clip clip;
void playMusic(String musicLocation)
{
try{
File musicPath = new File(musicLocation);
if(musicPath.exists())
{
AudioInputStream audioInput = AudioSystem.getAudioInputStream(musicPath);
clip = AudioSystem.getClip();
clip.open(audioInput);
clip.start();
clip.loop(Clip.`LOOP_CONTINUOUSLY`);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
void pauseMusic(String musicLocation2)
{
long clipTimePosition = clip.getMicrosecondPosition();
clip.stop();
}
==============
//this is in a different private method called Options
panel.setButtonsActionListener2(**new** ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
frame.dispose();
TowerDefense musicObject = new TowerDefense();
musicObject.pauseMusic(filepath);
Options();
}
});
I was expecting an output of the clip stopping and then you can either make it play again or keep it muted. In this case it just says error when I press the "mute" button.
So, in the code that runs when you click your mute button, you are making a new TowerDefense object that is supplied the music's filepath. Here is the issue with that. The clip that is already playing exists in the program. Creating a new TowerDefense object will not automatically give you access to the clip that is playing.
Ensure that you call the pauseMusic method on the same object where you called the playMusic method.
Thus, if you already have created a TowerDefense object in the program and called playMusic, then give your action listener access to that object and use the existing object to call pauseMusic.
so I am making a birthday present for a programmer friend of mine. I am not that good with code but I made a window + gif + sound. But once I test it on another PC the sound won't work anymore, but the JAR file is big enough to contain the WAV. PLease help me, I really want to make a nice birthday gift. Here is the Sound code + main
public static void play() {
try {
File file = new File("C:/Users/timma/IdeaProjects/BirthdayAshley/1" + ".wav");
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(file));
clip.start();
Thread.sleep(clip.getMicrosecondLength());
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public static void main(String[] args){
JFrame jf = new JFrame ("Happy Birthday");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(617,345);
jf.add(new Birthday());
jf.setVisible(true);
jf.setResizable(false);
play();
}
If the WAV is inside a JAR, it can't be referenced via a file.
But you can open it via Class.getResourceAsStream(). Everything else should stay the same.
InputStream stream =
SomeClassInTheSameJar.class.getResourceAsStream("/BirthdayAshley/1.wav");
use <MyClass>.class().getAsStream("/1.wav") to load the file. So it will loaded from your jar not with an absolut Path that not exists.
clip.open(AudioSystem.getAudioInputStream(<MyClass>.class.getAsStream("/1.wav")));
I'm relatively new to java (I took a 1 semester online class, so I know the basic structure of the language but my knowledge has lots of gaps). I'm trying to write a simple ear training application for a class in microtonal music I'm taking, and I obviously need to be able to play sound with this application. Looking on the web, a lot of the info I've found is out of date and I'm having trouble figuring out the APIs for Clip, Dataline, etc. (again, I'm new!) Is there a simple way to load sounds onto some kind of object (like an AudioClip maybe?) so they can be played back when necessary? If it's more complicated than that, I would appreciate being directed to resources that would help me figure how this process works.
You can use this method to play a audio clip using java application
public static synchronized void playSound(final String url) {
new Thread(new Runnable() {
// The wrapper thread is unnecessary, unless it blocks on the
// Clip finishing; see comments.
public void run() {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(
Main.class.getResourceAsStream("/path/to/sounds/" + url));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}).start();
}
Here's another tutorial on java how to add audio clips. You can check this too Tutorial in playing sounds in Java
You will need to import the following:
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import java.io.File;
import java.io.FileNotFoundException;
I created a method for playing the audio clip, as shown below:
public static void myMusic() throws FileNotFoundException {
try {
File wavFile = new File(/*file path*/);
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(wavFile));
clip.start();
} catch (Exception e) {
System.out.println(e);
}
}
Let's say for example, if your audio clip's file name is music.wav, your file path may be:
File wavFile = new File("music.wav");
Finally, to play the audio clip, you will need to call the method.
Sound does not play when I run the JAR, but it does when I run it in eclipse.
Here is where I load the clips:
public void init(){
System.out.println("grabbing Music");
String currentDir = new File("").getAbsolutePath();
name=new File(currentDir+"\\music\\").list();
clip=new Clip[name.length];
soundFile=new File[name.length];
for(int x=0;x<name.length;x++){
System.out.println(currentDir+"\\music\\"+name[x]);
try {
soundFile[x]= new File(currentDir+"\\music\\"+name[x]);
AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile[x]);
DataLine.Info info= new DataLine.Info(Clip.class, sound.getFormat());
clip[x] = (Clip) AudioSystem.getLine(info);
clip[x].open(sound);
clip[x].addLineListener(new LineListener(){
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
event.getLine().close();
}
}
});
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
}
}
}
I do not get any errors when running it in Eclipse. There should be no possibility of an invalid directory error, so what is wrong?
-When the jar is run in CMD i get no errors.
edit: I feel like I am loading the audio wrong, hence why I pasted the code I used to load the files in. In my searches I haven't seen anyone use File to load in a sound file. Wonder if that is the problem?
First thing that goes into my mind is that you didn't attached your sound library classes into your jar.
In order to run your current code, the folder music should be in the same folder the jar file is located in.
Another solution is to package your music folder inside the jar file and then change your code to:
InputStream is = getClass().getResourceAsStream("/music/" + name[x]);
AudioInputStream sound = AudioSystem.getAudioInputStream(is);
How about-
Right click on your project in Eclipse. Then New -> Source Folder.
Name the source folder anything. e.g. music_src.
Copy or drag the entire music directory in music_src. Then make the jar.
File systems have a hard time looking into jars.
Try using URL instead. A URL can locate a location within a jar. This happens a lot with folks trying to access resources in jars for the first time.
Otherwise things look fine.
I have a little question, I am building an app with the swing builder in Netbeans(note: it is Java). In this app I use an audio file I put in the main project folder, but when I start the jar, the audio file is not working, as if it's not included.
Does anyone know how I can fix this?
Any help will be greatly appreciated,
Black Magic
make sure that you have audio files in folder with jar and that path is correct. I used this method to play sounds:
public static synchronized void playSound(final File file)
{
new Thread(new Runnable()
{
#Override
public void run()
{
try
{
AudioInputStream inputStream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(inputStream);
clip.start();
} catch (Exception e)
{
System.err.println(e.getMessage());
}
}
}
)
.start();
}
In code i play sound using: playSound(new File("sounds/noise.wav"));
So i place my folder with noise.wav in folder with *.jar and it all works.