Eclipse IDE java equivalent of PHP include? - java

I've been digging around but can't find anything useful.
I'm working on an Android App.
Basically I have a package and there are three java files in it so far; my main screen page, a settings page and what I have called my 'subs.java' where I am putting useful functions, routines.
What I am trying to do is create this 'subs.java' file where routines that get used in more than one place can be stored.
So I have my main app page and I have a settings page. Both of these 'pages' need to use these common functions.
So I was going to put them in my 'subs.java' so I don't end up doubling up code.
Where I am stuck is now I have this subs.java file how do I link to it ?
In PHP if I want to use another file I just include it and I have access to all it's functions.
I suppose I am trying to build up a library, but Java is new to me.
How then would I do this in Eclipse/Java please ?
Here's my subs file, with some useful functions that I found else where :
package com.example.helloandroid;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
public class Subs extends Activity {
// Read settings
public String ReadSettings(Context context){
FileInputStream fIn = null;
InputStreamReader isr = null;
char[] inputBuffer = new char[255];
String data = null;
try {
fIn = openFileInput("settings.dat");
isr = new InputStreamReader(fIn);
isr.read(inputBuffer);
data = new String(inputBuffer);
Toast.makeText(context, "Settings read",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Settings not read",Toast.LENGTH_SHORT).show();
}
finally {
try {
isr.close();
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return data;
}
// Save settings
public void WriteSettings(Context context, String data){
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try {
fOut = openFileOutput("settings.dat",MODE_PRIVATE);
osw = new OutputStreamWriter(fOut);
osw.write(data);
osw.flush();
Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show();
}
finally {
try {
osw.close();
fOut.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}

The closest thing to PHP's include in Java is import. Read more about using import and package in Java.

If you've created a project as a package then any class using that package can access any other ones. So if you had SomeFileA.java and it uses package com.something.me, and SomeFileB.java that uses package com.something.me then they can reference each other. Typically Eclipse will auto-add any imports if you just flat out write SomeFileB b = new SomeFileB(); inside SomeFileA. If not you can just do use
import com.something.me.SomeFileB;

You would use the import statement to import your subs class. Then you can refer to any function in the subs class as subs.functionName()
If subs.java is in the same folder as your other java files, you can simply type import subs.
Read more about packages and imports at http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter05/packagesImport.html

What about "import" ? You can import a simple class, not only a library...
Put your common routines as static methods in a class ("MyAppHelper" for example), and call them in your "screens" :
MyAppHelper.function1(...)

Related

How to play a .mp3 file in Java [duplicate]

How can I play an .mp3 and a .wav file in my Java application? I am using Swing. I tried looking on the internet, for something like this example:
public void playSound() {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("D:/MusicPlayer/fml.mp3").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch(Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
}
But, this will only play .wav files.
The same with:
http://www.javaworld.com/javaworld/javatips/jw-javatip24.html
I want to be able to play both .mp3 files and .wav files with the same method.
Java FX has Media and MediaPlayer classes which will play mp3 files.
Example code:
String bip = "bip.mp3";
Media hit = new Media(new File(bip).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
You will need the following import statements:
import java.io.File;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
I wrote a pure java mp3 player: mp3transform.
Using standard javax.sound API, lightweight Maven dependencies, completely Open Source (Java 7 or later required), this should be able to play most WAVs, OGG Vorbis and MP3 files:
pom.xml:
<!--
We have to explicitly instruct Maven to use tritonus-share 0.3.7-2
and NOT 0.3.7-1, otherwise vorbisspi won't work.
-->
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>tritonus-share</artifactId>
<version>0.3.7-2</version>
</dependency>
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>mp3spi</artifactId>
<version>1.9.5-1</version>
</dependency>
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>vorbisspi</artifactId>
<version>1.0.3-1</version>
</dependency>
Code:
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine.Info;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import static javax.sound.sampled.AudioSystem.getAudioInputStream;
import static javax.sound.sampled.AudioFormat.Encoding.PCM_SIGNED;
public class AudioFilePlayer {
public static void main(String[] args) {
final AudioFilePlayer player = new AudioFilePlayer ();
player.play("something.mp3");
player.play("something.ogg");
}
public void play(String filePath) {
final File file = new File(filePath);
try (final AudioInputStream in = getAudioInputStream(file)) {
final AudioFormat outFormat = getOutFormat(in.getFormat());
final Info info = new Info(SourceDataLine.class, outFormat);
try (final SourceDataLine line =
(SourceDataLine) AudioSystem.getLine(info)) {
if (line != null) {
line.open(outFormat);
line.start();
stream(getAudioInputStream(outFormat, in), line);
line.drain();
line.stop();
}
}
} catch (UnsupportedAudioFileException
| LineUnavailableException
| IOException e) {
throw new IllegalStateException(e);
}
}
private AudioFormat getOutFormat(AudioFormat inFormat) {
final int ch = inFormat.getChannels();
final float rate = inFormat.getSampleRate();
return new AudioFormat(PCM_SIGNED, rate, 16, ch, ch * 2, rate, false);
}
private void stream(AudioInputStream in, SourceDataLine line)
throws IOException {
final byte[] buffer = new byte[4096];
for (int n = 0; n != -1; n = in.read(buffer, 0, buffer.length)) {
line.write(buffer, 0, n);
}
}
}
References:
http://odoepner.wordpress.com/2013/07/19/play-mp3-using-javax-sound-sampled-api-and-mp3spi/
you can play .wav only with java API:
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
code:
AudioInputStream audioIn = AudioSystem.getAudioInputStream(MyClazz.class.getResource("music.wav"));
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
And play .mp3 with jLayer
It's been a while since I used it, but JavaLayer is great for MP3 playback
I would recommend using the BasicPlayerAPI. It's open source, very simple and it doesn't require JavaFX.
http://www.javazoom.net/jlgui/api.html
After downloading and extracting the zip-file one should add the following jar-files to the build path of the project:
basicplayer3.0.jar
all the jars from the lib directory (inside BasicPlayer3.0)
Here is a minimalistic usage example:
String songName = "HungryKidsofHungary-ScatteredDiamonds.mp3";
String pathToMp3 = System.getProperty("user.dir") +"/"+ songName;
BasicPlayer player = new BasicPlayer();
try {
player.open(new URL("file:///" + pathToMp3));
player.play();
} catch (BasicPlayerException | MalformedURLException e) {
e.printStackTrace();
}
Required imports:
import java.net.MalformedURLException;
import java.net.URL;
import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.basicplayer.BasicPlayerException;
That's all you need to start playing music. The Player is starting and managing his own playback thread and provides play, pause, resume, stop and seek functionality.
For a more advanced usage you may take a look at the jlGui Music Player. It's an open source WinAmp clone: http://www.javazoom.net/jlgui/jlgui.html
The first class to look at would be PlayerUI (inside the package javazoom.jlgui.player.amp).
It demonstrates the advanced features of the BasicPlayer pretty well.
The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29
Here is the code for the class
public class SimplePlayer {
public SimplePlayer(){
try{
FileInputStream fis = new FileInputStream("File location.");
Player playMP3 = new Player(fis);
playMP3.play();
} catch(Exception e){
System.out.println(e);
}
}
}
and here are the imports
import javazoom.jl.player.*;
import java.io.FileInputStream;
To give the readers another alternative, I am suggesting JACo MP3 Player library, a cross platform java mp3 player.
Features:
very low CPU usage (~2%)
incredible small library (~90KB)
doesn't need JMF (Java Media Framework)
easy to integrate in any application
easy to integrate in any web page (as applet).
For a complete list of its methods and attributes you can check its documentation here.
Sample code:
import jaco.mp3.player.MP3Player;
import java.io.File;
public class Example1 {
public static void main(String[] args) {
new MP3Player(new File("test.mp3")).play();
}
}
For more details, I created a simple tutorial here that includes a downloadable sourcecode.
UPDATE(2022)
The download link at that page does not work anymore, but there is a sourceforge project
Using MP3 Decoder/player/converter Maven Dependency.
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class PlayAudio{
public static void main(String[] args) throws FileNotFoundException {
try {
FileInputStream fileInputStream = new FileInputStream("mp.mp3");
Player player = new Player((fileInputStream));
player.play();
System.out.println("Song is playing");
while(true){
System.out.println(player.getPosition());
}
}catch (Exception e){
System.out.println(e);
}
}
}
You need to install JMF first (download using this link)
File f = new File("D:/Songs/preview.mp3");
MediaLocator ml = new MediaLocator(f.toURL());
Player p = Manager.createPlayer(ml);
p.start();
don't forget to add JMF jar files
Do a search of freshmeat.net for JAVE (stands for Java Audio Video Encoder) Library (link here). It's a library for these kinds of things. I don't know if Java has a native mp3 function.
You will probably need to wrap the mp3 function and the wav function together, using inheritance and a simple wrapper function, if you want one method to run both types of files.
To add MP3 reading support to Java Sound, add the mp3plugin.jar of the JMF to the run-time class path of the application.
Note that the Clip class has memory limitations that make it unsuitable for more than a few seconds of high quality sound.
I have other methods for that, the first is :
public static void playAudio(String filePath){
try{
InputStream mus = new FileInputStream(new File(filePath));
AudioStream aud = new AudioStream(mus);
}catch(Exception e){
JOptionPane.showMessageDialig(null, "You have an Error");
}
And the second is :
try{
JFXPanel x = JFXPanel();
String u = new File("021.mp3").toURI().toString();
new MediaPlayer(new Media(u)).play();
} catch(Exception e){
JOPtionPane.showMessageDialog(null, e);
}
And if we want to make loop to this audio we use this method.
try{
AudioData d = new AudioStream(new FileInputStream(filePath)).getData();
ContinuousAudioDataStream s = new ContinuousAudioDataStream(d);
AudioPlayer.player.start(s);
} catch(Exception ex){
JOPtionPane.showMessageDialog(null, ex);
}
if we want to stop this loop we add this libreries in the try:
AudioPlayer.player.stop(s);
for this third method we add the folowing imports :
import java.io.FileInputStream;
import sun.audio.AudioData;
import sun.audio.AudioStream;
import sun.audio.ContinuousAudioDataStream;
Nothing worked. but this one perfectly 👌
google and download Jlayer library first.
import javazoom.jl.player.Player;
import java.io.FileInputStream;
public class MusicPlay {
public static void main(String[] args) {
try{
FileInputStream fs = new FileInputStream("audio_file_path.mp3");
Player player = new Player(fs);
player.play();
} catch (Exception e){
// catch exceptions.
}
}
}
Use this library: import sun.audio.*;
public void Sound(String Path){
try{
InputStream in = new FileInputStream(new File(Path));
AudioStream audios = new AudioStream(in);
AudioPlayer.player.start(audios);
}
catch(Exception e){}
}

util.Properties bug corrupting .properties file on win10

This bug is happening only in win10. Currently in win7 it does not happen.
Essentially I write some text that the user has inputted in various fields.
I use this to save all the info the user wrote, so when the application is relaunched the info is already there.
Also, I call this class every time the user clicks a button.
With normal behavior, the application runs fine on win7, and it saves everything properly. With win10 though, saving effectively "corrupts" the file, or at least, it makes it empty.
package whatever;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class SaveFile {
public static void mainSave(String[] args) {
Properties prop = new Properties();
OutputStream output = null;
try {
String instaPathCombined = "config.properties";
output = new FileOutputStream(instaPathCombined);
// set the properties value, the get methods all retrieve a string.
prop.setProperty("a", UI.geta());
prop.setProperty("b", UI.getb());
prop.setProperty("c", UI.getc());
prop.setProperty("d", UI.getd());
prop.setProperty("e", UI.gete());
prop.setProperty("f", UI.getf());
prop.setProperty("g", UI.getg());
prop.setProperty("h", UI.geth());
prop.setProperty("i", UI.geti());
prop.setProperty("j", UI.getj());
prop.setProperty("k", UI.getk());
prop.setProperty("l", UI.getl());
prop.setProperty("m", UI.getm());
prop.setProperty("n", UI.getn());
prop.setProperty("o", UI.geto());
prop.setProperty("p", UI.getp());
prop.setProperty("q", UI.getq());
prop.setProperty("r", UI.getr());
prop.setProperty("s", UI.gets());
prop.setProperty("t", UI.gett());
prop.setProperty("u", UI.getu());
prop.setProperty("v", UI.getv());
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I have no idea on why it does this.
Also, this is literally a win10 issue, no other factors matter here, as I tried it on a VM with a fresh win10 installation and it happened.

SFNTLY: How to convert any font that gets uploaded to "WOFF" format?

I can not find any documenration on this library (https://code.google.com/p/sfntly/). I've been taking stabs at it for 2 days now. I'm trying to convert any font that gets uploaded to "WOFF" format.
Could someone shed some light?
I successfully converted my TTF into a WOFF file by following these steps:
Download and install ant following "The Short Story" steps (http://ant.apache.org/manual/install.html#getBinary)
Download SFNTLY via SVN checkout (https://code.google.com/p/sfntly/source/checkout) and followed the steps contained into the file "sfntly\java\quickstart.txt"
Created a new java project and imported the following four jars I created following the previous steps into my project:
sfntly.jar
woffconverter.jar
guava-16.0.1.jar
I slightly tweaked display_name code which contained a few syntax mistakes.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.google.common.io.Files;
import com.google.typography.font.sfntly.Font;
import com.google.typography.font.sfntly.FontFactory;
import com.google.typography.font.sfntly.data.WritableFontData;
import com.google.typography.font.tools.conversion.woff.WoffWriter;
public class Main {
public static void main(String[] args) {
WoffWriter ww = new WoffWriter();
FontFactory fontFactory = FontFactory.getInstance();
byte[] bytes;
try {
bytes = Files.toByteArray(new File("C:\\FontName.TTF"));
Font font = fontFactory.loadFonts(bytes)[0];
WritableFontData wfd = ww.convert(font);
FileOutputStream fs = new FileOutputStream("out.fnt");
wfd.copyTo(fs);
fs.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
After reading the source code of SFNTLY I am no expert in sfntly, so use my answer at your risk :).
I would convert the font with WoffWriter#convert() to writeable font data, then copy the wfd to outputstream.
WoffWriter ww = new WoffWriter();
WriteableFontData wfd = ww.convert(yourFont);
try {
FileOutPutStream fs = new FileOutputStream("out.fnt");
wfd.copyTo(fs, wfd);
fs.close();
} catch (IOException e) {
}

How to handle this error on kabeja?

I need to generate SVG from given DXF file. I try to archive that by using kabeja package. This is the code that they gave on their web page.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.xml.sax.ContentHandler;
import org.kabeja.dxf.DXFDocument;
import org.kabeja.parser.DXFParseException;
import org.kabeja.parser.Parser;
import org.kabeja.parser.ParserBuilder;
import org.kabeja.svg.SVGGenerator;
import org.kabeja.xml.SAXGenerator;
public class MyClass{
public MyClass(){
...
}
public void parseFile(String sourceFile) {
Parser parser = ParserBuilder.createDefaultParser();
try {
parser.parse(new FileInputStream(sourceFile));
DXFDocument doc = parser.getDocument();
//the SVG will be emitted as SAX-Events
//see org.xml.sax.ContentHandler for more information
ContentHandler myhandler = new ContentHandlerImpl();
//the output - create first a SAXGenerator (SVG here)
SAXGenerator generator = new SVGGenerator();
//setup properties
generator.setProperties(new HashMap());
//start the output
generator.generate(doc,myhandler);
} catch (DXFParseException e) {
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
Hear is the code that provided by the kabeja development group on sourceforge web site. But in above code I noticed that some of the classes are missing on their new package. for example
ContentHandler myhandler = new ContentHandlerImpl();
In this line it create contentHandlerImpl object but with new kabeja package it dosn't have that class.So because of this it doesn't generate SVG file. So could some one explain me how to archive my target by using this package.
Try to read symbol ContentHandlerImpl not found from kabeja's forum

Playing .mp3 and .wav in Java?

How can I play an .mp3 and a .wav file in my Java application? I am using Swing. I tried looking on the internet, for something like this example:
public void playSound() {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("D:/MusicPlayer/fml.mp3").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch(Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
}
But, this will only play .wav files.
The same with:
http://www.javaworld.com/javaworld/javatips/jw-javatip24.html
I want to be able to play both .mp3 files and .wav files with the same method.
Java FX has Media and MediaPlayer classes which will play mp3 files.
Example code:
String bip = "bip.mp3";
Media hit = new Media(new File(bip).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
You will need the following import statements:
import java.io.File;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
I wrote a pure java mp3 player: mp3transform.
Using standard javax.sound API, lightweight Maven dependencies, completely Open Source (Java 7 or later required), this should be able to play most WAVs, OGG Vorbis and MP3 files:
pom.xml:
<!--
We have to explicitly instruct Maven to use tritonus-share 0.3.7-2
and NOT 0.3.7-1, otherwise vorbisspi won't work.
-->
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>tritonus-share</artifactId>
<version>0.3.7-2</version>
</dependency>
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>mp3spi</artifactId>
<version>1.9.5-1</version>
</dependency>
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>vorbisspi</artifactId>
<version>1.0.3-1</version>
</dependency>
Code:
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine.Info;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import static javax.sound.sampled.AudioSystem.getAudioInputStream;
import static javax.sound.sampled.AudioFormat.Encoding.PCM_SIGNED;
public class AudioFilePlayer {
public static void main(String[] args) {
final AudioFilePlayer player = new AudioFilePlayer ();
player.play("something.mp3");
player.play("something.ogg");
}
public void play(String filePath) {
final File file = new File(filePath);
try (final AudioInputStream in = getAudioInputStream(file)) {
final AudioFormat outFormat = getOutFormat(in.getFormat());
final Info info = new Info(SourceDataLine.class, outFormat);
try (final SourceDataLine line =
(SourceDataLine) AudioSystem.getLine(info)) {
if (line != null) {
line.open(outFormat);
line.start();
stream(getAudioInputStream(outFormat, in), line);
line.drain();
line.stop();
}
}
} catch (UnsupportedAudioFileException
| LineUnavailableException
| IOException e) {
throw new IllegalStateException(e);
}
}
private AudioFormat getOutFormat(AudioFormat inFormat) {
final int ch = inFormat.getChannels();
final float rate = inFormat.getSampleRate();
return new AudioFormat(PCM_SIGNED, rate, 16, ch, ch * 2, rate, false);
}
private void stream(AudioInputStream in, SourceDataLine line)
throws IOException {
final byte[] buffer = new byte[4096];
for (int n = 0; n != -1; n = in.read(buffer, 0, buffer.length)) {
line.write(buffer, 0, n);
}
}
}
References:
http://odoepner.wordpress.com/2013/07/19/play-mp3-using-javax-sound-sampled-api-and-mp3spi/
you can play .wav only with java API:
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
code:
AudioInputStream audioIn = AudioSystem.getAudioInputStream(MyClazz.class.getResource("music.wav"));
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
And play .mp3 with jLayer
It's been a while since I used it, but JavaLayer is great for MP3 playback
I would recommend using the BasicPlayerAPI. It's open source, very simple and it doesn't require JavaFX.
http://www.javazoom.net/jlgui/api.html
After downloading and extracting the zip-file one should add the following jar-files to the build path of the project:
basicplayer3.0.jar
all the jars from the lib directory (inside BasicPlayer3.0)
Here is a minimalistic usage example:
String songName = "HungryKidsofHungary-ScatteredDiamonds.mp3";
String pathToMp3 = System.getProperty("user.dir") +"/"+ songName;
BasicPlayer player = new BasicPlayer();
try {
player.open(new URL("file:///" + pathToMp3));
player.play();
} catch (BasicPlayerException | MalformedURLException e) {
e.printStackTrace();
}
Required imports:
import java.net.MalformedURLException;
import java.net.URL;
import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.basicplayer.BasicPlayerException;
That's all you need to start playing music. The Player is starting and managing his own playback thread and provides play, pause, resume, stop and seek functionality.
For a more advanced usage you may take a look at the jlGui Music Player. It's an open source WinAmp clone: http://www.javazoom.net/jlgui/jlgui.html
The first class to look at would be PlayerUI (inside the package javazoom.jlgui.player.amp).
It demonstrates the advanced features of the BasicPlayer pretty well.
The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29
Here is the code for the class
public class SimplePlayer {
public SimplePlayer(){
try{
FileInputStream fis = new FileInputStream("File location.");
Player playMP3 = new Player(fis);
playMP3.play();
} catch(Exception e){
System.out.println(e);
}
}
}
and here are the imports
import javazoom.jl.player.*;
import java.io.FileInputStream;
To give the readers another alternative, I am suggesting JACo MP3 Player library, a cross platform java mp3 player.
Features:
very low CPU usage (~2%)
incredible small library (~90KB)
doesn't need JMF (Java Media Framework)
easy to integrate in any application
easy to integrate in any web page (as applet).
For a complete list of its methods and attributes you can check its documentation here.
Sample code:
import jaco.mp3.player.MP3Player;
import java.io.File;
public class Example1 {
public static void main(String[] args) {
new MP3Player(new File("test.mp3")).play();
}
}
For more details, I created a simple tutorial here that includes a downloadable sourcecode.
UPDATE(2022)
The download link at that page does not work anymore, but there is a sourceforge project
Using MP3 Decoder/player/converter Maven Dependency.
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class PlayAudio{
public static void main(String[] args) throws FileNotFoundException {
try {
FileInputStream fileInputStream = new FileInputStream("mp.mp3");
Player player = new Player((fileInputStream));
player.play();
System.out.println("Song is playing");
while(true){
System.out.println(player.getPosition());
}
}catch (Exception e){
System.out.println(e);
}
}
}
You need to install JMF first (download using this link)
File f = new File("D:/Songs/preview.mp3");
MediaLocator ml = new MediaLocator(f.toURL());
Player p = Manager.createPlayer(ml);
p.start();
don't forget to add JMF jar files
Do a search of freshmeat.net for JAVE (stands for Java Audio Video Encoder) Library (link here). It's a library for these kinds of things. I don't know if Java has a native mp3 function.
You will probably need to wrap the mp3 function and the wav function together, using inheritance and a simple wrapper function, if you want one method to run both types of files.
To add MP3 reading support to Java Sound, add the mp3plugin.jar of the JMF to the run-time class path of the application.
Note that the Clip class has memory limitations that make it unsuitable for more than a few seconds of high quality sound.
I have other methods for that, the first is :
public static void playAudio(String filePath){
try{
InputStream mus = new FileInputStream(new File(filePath));
AudioStream aud = new AudioStream(mus);
}catch(Exception e){
JOptionPane.showMessageDialig(null, "You have an Error");
}
And the second is :
try{
JFXPanel x = JFXPanel();
String u = new File("021.mp3").toURI().toString();
new MediaPlayer(new Media(u)).play();
} catch(Exception e){
JOPtionPane.showMessageDialog(null, e);
}
And if we want to make loop to this audio we use this method.
try{
AudioData d = new AudioStream(new FileInputStream(filePath)).getData();
ContinuousAudioDataStream s = new ContinuousAudioDataStream(d);
AudioPlayer.player.start(s);
} catch(Exception ex){
JOPtionPane.showMessageDialog(null, ex);
}
if we want to stop this loop we add this libreries in the try:
AudioPlayer.player.stop(s);
for this third method we add the folowing imports :
import java.io.FileInputStream;
import sun.audio.AudioData;
import sun.audio.AudioStream;
import sun.audio.ContinuousAudioDataStream;
Nothing worked. but this one perfectly 👌
google and download Jlayer library first.
import javazoom.jl.player.Player;
import java.io.FileInputStream;
public class MusicPlay {
public static void main(String[] args) {
try{
FileInputStream fs = new FileInputStream("audio_file_path.mp3");
Player player = new Player(fs);
player.play();
} catch (Exception e){
// catch exceptions.
}
}
}
Use this library: import sun.audio.*;
public void Sound(String Path){
try{
InputStream in = new FileInputStream(new File(Path));
AudioStream audios = new AudioStream(in);
AudioPlayer.player.start(audios);
}
catch(Exception e){}
}

Categories

Resources