How to play a background music when the program run? in java - java

I am making a card game, and it's almost done. The last thing I want to do is play some background music. Now if I copy the file into the default package and make a single jar file of the game, will the music play on all computers? Currently, on my PC it's running without any problem by giving a specific path for the file like "C:\\samp.wav";. But I am worried that if I make a jar file and run it on another PC it won't work properly. I think there will be a FileNotFoundException. Am I right or wrong?
For the card's image I am using this line:
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/1.jpg")));
Those pictures I have inserted into my default package. I want to do the same for the music file, but how? I am using NetBeans.

You should include the wav file inside your application jar. This way you won't have to manage the copy of the file in the user's file system (keep in mind that, for example, in UNIX, Mac, etc. you can't access to the hard drive through C:/...).
For example, if you place the wav file in the root of the app jar (app.jar/samp.wav):
InputStream is = getClass().getClassLoader().getResourceAsStream("samp.wav");
or, if you had a "sounds" directory in the app jar root (app.jar/sounds/samp.wav):
InputStream is = getClass().getClassLoader().getResourceAsStream("sounds/samp.wav");
Check this post for extra information about playing wav files with Java (though for your question, I think you have already solved this problem). Consider as well playing it in a separate thread. Check also this web for examples about managing media files in Java.

import javax.swing.*;
import sun.audio.*;
import java.awt.event.*;
import java.io.*;
public class Sound {
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(200,200);
JButton button = new JButton("Click me");
frame.add(button);
button.addActionListener(new AL());
frame.setVisible(true);
}
public static class AL implements ActionListener{
public final void actionPerformed(ActionEvent e){
music();
}
}
public static void music(){
AudioPlayer MGP = AudioPlayer.player;
AudioStream BGM;
AudioData MD;
ContinuousAudioDataStream loop = null;
try{
BGM = new AudioStream(new FileInputStream("C:\\test\\ha.wav"));
MD = BGM.getData();
loop = new ContinuousAudioDataStream(MD);
}catch(IOException error){
System.out.print("file not found");
}
MGP.start(loop);
}
}

Related

"Can not resolve symbol" error in Vaadin Upload tutorial

I am using Vaadin in Java and I am following this tutorial: Vaadin Upload
So I have created a new Class name Uploader. But there is some stuff which doesn't work in my code, I put what is not working in ** text **:
import com.vaadin.server.FileResource;
import com.vaadin.ui.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
/**
* Created by mflamant on 15/05/2017.
*/
public class Uploader {
final Embedded image = new Embedded("Uploaded image");
**image.setVisible(false);**
class Image implements Upload.Receiver, Upload.SucceededListener{
public File file;
public OutputStream receiveUpload(String filename, String mimeType){
FileOutputStream fos = null;
try{
file = new File(filename);
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e){
e.printStackTrace();
return null;
}
return fos;
}
public void uploadSucceeded(Upload.SucceededEvent event){
image.setVisible(true);
image.setSource(new FileResource(file));
}
};
Image receiver = new Image();
Upload upload = new Upload("Upload image here", receiver);
**upload.setButtonCaption("Start Upload");**
**upload.SucceededListener(receiver);**
Panel panel = new Panel("Image storage");
Layout panelContent = new VerticalLayout();
**panelContent.addComponents(upload, image);**
**panel.setContent;**
}
The error I have is "Can not resolve symbol". Can you explain to me why these lines aren't working?
Upload example doesn't list the whole code of the application. It only includes the code snippets specific to the Upload component itself. These code snippets are not expected to work if you just paste them into your class.
This example is a part of Vaadin Documentation and you're expected to understand the basics at the time you reach this part.
Example code is intended to work as a part of a method that builds a Vaadin component. The particular error is that you can only call methods, like image.setVisible(false) from an executable code block. You can't just paste them in your class declaration, that's not a valid Java code.
Tutorial links to a working code on Github. As you can see it contains all the necessary initialization in place:
public class UploadExample extends CustomComponent implements BookExampleBundle {
private static final long serialVersionUID = -4292553844521293140L;
public void init (String context) {
//... omitted for brevity
basic(layout);
//... omitted for brevity
}
void basic(VerticalLayout layout) {
final Image image = new Image("Uploaded Image");
//the rest of the example code goes here
Please, note that this class alone still doesn't work as a standalone application. This is just one of the components.
So, what you can do now:
Complete Vaadin Tutorial first. This should help you grasp the concepts.
Read the Introduction part of the docs first. This will help you build the working application. Then you can jump to specific components.
Clone Book Examples application from Github and then try to figure out how it works.

Java executable .jar file does not play MP3 file from external resource

I have a Java project in Netbeans which includes a User interface. From the interface the user can play an MP3 file that is stored in a folder "data" within the projects working directory.
For playing the file I have a class that creates an MP3 player and makes use of the JLayer.jar.
import java.awt.Component;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.swing.JFileChooser;
import javazoom.jl.player.Player;
public class MP3Player {
private String filename;
private Player player;
// a default constructor
public MP3Player() {}
// Constructor takes a given file name
public MP3Player(String filename) {
this.filename = filename;
}
public void close() { if (player != null) player.close(); }
// play the JLayerMP3 file to the sound card
public void play() {
try {
InputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);
player = new Player(bis);
}
catch (Exception e) {
System.out.println("\n Problem in playing: " + filename);
System.out.println(e);
}
}
public void play(String mp3filename) {
try {
InputStream fis = new FileInputStream(mp3filename);
BufferedInputStream bis = new BufferedInputStream(fis);
player = new Player(bis);
}
catch (Exception e) {
System.out.println("Problem in playing: " + mp3filename);
System.out.println(e);
}
// creata a thread to play music in background
new Thread() {
public void run() {
try { player.play(); }
catch (Exception e) { System.out.println(e); }
}
}.start();
}
Within the UI class I have a play button with an action method within which I create an MP3 player object. I then pass the filepath to the MP3 Player
MP3Player mp3 = new MP3Player();
mp3.play("data/audio/" + filepath);
As long as I run this project in Netbeans, it works fine and the music plays.
But once I create a jar file it does not play the music.
I found some other posts about similar problems
For example: Loading an mp3 file with JLayer from inside the Jar
But contrary to them I don't want to include the MP3 files in the JAR. It should take the files from a local folder "data".
I place the "data" folder containing the mp3.files in the same directory as the jar file. So the filepath is exactly the same as when I have it in the Netbeans project's working directory and run it from Netbeans (as I said there is no problem then).
And the JAR gets all the other data like textfiles and images without any problems from the local "data" folder.
Any help is highly appreciated.
Netbeans creates dirctory like this: YourProjectDir/dist/YourProject.jar. Your libraries are placed inside YourProjectDir/dist/lib/otherlibrary.jar. Create your data folder inside your YourProjectDir i.e. your media files will remain inside YourProjectDir/data/audio/.
What you do, just create a batch file with any name.
#echo off
START/MAX dist\YourProject.jar
Place the Batch file inside YourProjectDir. Now run the Batch file.

How do you add music to a JFrame?

import java.awt.*;
import javax.swing.*;
public class TestFrame1 {
public static void main(String[] args) {
JFrame frame = new JFrame("Test Frame 1");
frame.setSize(200, 100);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I need some help adding music to jframe. i been looking only for a good tutorial, and none of them seem to work.
im using netbeans. here is my current code. i just want to add music to the frame no stop button for now. Thank you.
Have a look at Accessing Audio System Resources. Here are the available classes
Class Format
---------------------------------------------
AudioSystem WAV
Manager* MP3
MidiSystem Midi
javax.media.Manager requires Java Media Framework
The easiest options are AudioSystem or MidiSystem a they require no additional JAR files. Here is an example from the javasound tag link
public class LoopSound {
public static void main(String[] args) throws Exception {
URL url = new URL(
"http://pscode.org/media/leftright.wav");
Clip clip = AudioSystem.getClip();
// getAudioInputStream() also accepts a File or InputStream
AudioInputStream ais = AudioSystem.getAudioInputStream( url );
clip.open(ais);
clip.loop(Clip.LOOP_CONTINUOUSLY);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// A GUI element to prevent the Clip's daemon Thread
// from terminating at the end of the main()
JOptionPane.showMessageDialog(null, "Close to exit!");
}
});
}
}
To integrate the the audio with the JFrame, simply invoke Clip#loop when the application is started.
Try:
public static void playSong(URL media) {
Player mediaPlayer = Manager.createRealizedPlayer(media);
mediaPlayer.start()
}
So you should just be able to call that method and pass in the URL to the media, and then it should play (Note: I have not tested this code).
The imports you need are:
import javax.media.Player;
import java.net.URL;
I just remembered, you need to add the JMF .jar to your project. The JMF (Java Media Framework) has tools for playing music and (I think) video, among other things.
Here is a pretty extensive tutorial from IBM: http://www.ibm.com/developerworks/java/tutorials/j-jmf/
Towards the bottom, it has instructions on installing JMF, and then on the next page it shows you how to make basic audio.
Some more advice:
1) You need to add the mp3 plug in to play mp3s from the JMF. After adding the plug in .jar file to your project, this is the code you haft to add (I'm doing this from memory, so it may be wrong):
Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3);
Format input2 = new AudioFormat(AudioFormat.MPEG);
Format output = new AudioFormat(AudioFormat.LINEAR);
PlugInManager.addPlugIn(
"com.sun.media.codec.audio.mp3.JavaDecoder",
new Format[]{input1, input2},
new Format[]{output},
PlugInManager.CODEC
);
2) The last time I used it, the JMF download link was broken on the oracle website (it linked to the wrong page), so you may have to search around for the link on google.

How to set Icon to JFrame

I tried this way, but it didnt changed?
ImageIcon icon = new ImageIcon("C:\\Documents and Settings\\Desktop\\favicon(1).ico");
frame.setIconImage(icon.getImage());
Better use a .png file; .ico is Windows specific. And better to not use a file, but a class resource (can be packed in the jar of the application).
URL iconURL = getClass().getResource("/some/package/favicon.png");
// iconURL is null when not found
ImageIcon icon = new ImageIcon(iconURL);
frame.setIconImage(icon.getImage());
Though you might even think of using setIconImages for the icon in several sizes.
Try putting your images in a separate folder outside of your src folder. Then, use ImageIO to load your images. It should look like this:
frame.setIconImage(ImageIO.read(new File("res/icon.png")));
Finally I found the main issue in setting the jframe icon. Here is my code. It is similar to other codes but here are few things to mind the game.
this.setIconImage(new ImageIcon(getClass().getResource("Icon.png")).getImage());
1) Put this code in jframe WindowOpened event
2) Put Image in main folder where all of your form and java files are created e.g.
src\ myproject\ myFrame.form
src\ myproject\ myFrame.java
src\ myproject\ OtherFrame.form
src\ myproject\ OtherFrame.java
src\ myproject\ Icon.png
3) And most important that name of file is case sensitive that is icon.png won't work but Icon.png.
this way your icon will be there even after finally building your project.
This works for me.
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(".\\res\\icon.png"));
For the export jar file, you need to configure the build path to include the res folder and use the following codes.
URL url = Main.class.getResource("/icon.png");
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(url));
Yon can try following way,
myFrame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));
Here is the code I use to set the Icon of a JFrame
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
try{
setIconImage(ImageIO.read(new File("res/images/icons/appIcon_Black.png")));
}
catch (IOException e){
e.printStackTrace();
}
Just copy these few lines of code in your code and replace "imgURL" with Image(you want to set as jframe icon) location.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create the frame.
JFrame frame = new JFrame("A window");
//Set the frame icon to an image loaded from a file.
frame.setIconImage(new ImageIcon(imgURL).getImage());
I'm using the following utility class to set the icon for JFrame and JDialog instances:
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Scanner;
public class WindowUtilities
{
public static void setIconImage(Window window)
{
window.setIconImage(Toolkit.getDefaultToolkit().getImage(WindowUtilities.class.getResource("/Icon.jpg")));
}
public static String resourceToString(String filePath) throws IOException, URISyntaxException
{
InputStream inputStream = WindowUtilities.class.getClassLoader().getResourceAsStream(filePath);
return toString(inputStream);
}
// http://stackoverflow.com/a/5445161/3764804
private static String toString(InputStream inputStream)
{
try (Scanner scanner = new Scanner(inputStream, "UTF-8").useDelimiter("\\A"))
{
return scanner.hasNext() ? scanner.next() : "";
}
}
}
So using this becomes as simple as calling
WindowUtilities.setIconImage(this);
somewhere inside your class extending a JFrame.
The Icon.jpg has to be located in myproject\src\main\resources when using Maven for instance.
I use Maven and have the structure of the project, which was created by entering the command:
mvn archetype:generate
The required file icon.png must be put in the src/main/resources folder of your maven project.
Then you can use the next lines inside your project:
ImageIcon img = new ImageIcon(getClass().getClassLoader().getResource("./icon.png"));
setIconImage(img.getImage());
My project code is as below:
private void setIcon() {
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/slip/images/cage_settings.png")));
}
frame.setIconImage(new ImageIcon(URL).getImage());
/*
frame is JFrame
setIcon method, set a new icon at your frame
new ImageIcon make a new instance of class (so you can get a new icon from the url that you give)
at last getImage returns the icon you need
it is a "fast" way to make an icon, for me it is helpful because it is one line of code
*/
public FaceDetection() {
initComponents();
//Adding Frame Icon
try {
this.setIconImage(ImageIO.read(new File("WASP.png")));
} catch (IOException ex) {
Logger.getLogger(FaceDetection.class.getName()).log(Level.SEVERE, null, ex);
}
}'
this works for me.

Using music in a java program

I was trying out the method of creating a background music for a java program, but it displayed an IO excedption error when i clicked the play button.
package javaentertainment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.IOException;
import javax.swing.*;
import sun.audio.AudioData;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
public class Music
{
public static void main(String args[])
{
JFrame frame=new JFrame();
frame.setSize(100,100);
JButton button=new JButton("P L A Y");
frame.add(button);
button.addActionListener(new AL());
frame.show();
}
public static class AL implements ActionListener
{
public void actionPerformed(ActionEvent e) {
music();
}
}
public static void music()
{
AudioPlayer MGP=AudioPlayer.player;
AudioStream BGM;
AudioData MD;
ContinousAudioDataStream loop=null;
try
{
BGM = new AudioStream(new FileInputStream("Vision.wmv"));
MD=BGM.getData();
loop=new ContinousAudioDataStream(MD);
}
catch (IOException ex)
{
System.out.println(ex);
}
MGP.start(loop); // word loop was underlined by netbeans
}
}
When I run the program and click on play it displays the following error,
java.io.IOException: could not create audio stream from input stream
You should use JMF (Java Media Framework). For your interest: The list of accepted formats can be found here.
In short, it supports AIFF, AVI, GSM, MVR, MID, MPG, MP2, MOV, AU and WAV files.
But there is a workarond as stated here:
On a side note, if you add a
mime-setting in JMFRegistry to map
Windows Media content (such as .asf
and .wmv) to the content-type
"video/mpeg", JMF can actually play
Windows Media or any other DirectShow
file (and only file - http wont work).
I would be surprised if Java can hand Windows Media format samples - try converting the .wmv to a .wav file and see if it works then.
Just got this, as well.
java.io.IOException: could not create AudioData object
Appears from the source [1] that this means that "your audio file is size > 1 MB" and it doesn't like that for whatever reason. Maybe a bug [?] that they don't accomodate for this.
One work-around might be to use JMF instead, as suggested, if you want looping to work for large files anyway.
[1] http://www.docjar.com/docs/api/sun/audio/AudioStream.html#getData

Categories

Resources