Mp3 Player with Jlayer

if you want to play mp3 for bg music for your games this is what u need:

PLAY, STOP, RESUME, LOOP,
NOTE: you have to have installed jlayer1.0.1-1.jar

it works for music that is inside the jar ( for relative paths )



package com.ilusion2.audio;


import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

/**
 *this class is used to create a music player, with
 * play, stop, pause, loop, functionality, this class
 * must be used to put background music to a level
 * NOTE: the files to play must be in resources folder
 * @author pavulzavala
 */
public class MusicPlayer 
{
    
    private InputStream is;
    
    private Player player;
    private boolean repeat; 
    private boolean paused; 
    private long pauseLocation;
    private long totalSongLength;
    private String musicFilePath;
    
    //@TODO consider add a counter to play a song
    // X number of times

    /**
     * this method is used to play a song, if u want to
     * repeat this song,  set Repeat to true before 
     * call this method
     * NOTE: the files to play must be in resources folder
     * @param musicFilePath
     * @throws FileNotFoundException
     * @throws JavaLayerException
     * @throws IOException 
     * @throws java.net.URISyntaxException 
     */
    public void play( String musicFilePath ) throws FileNotFoundException, JavaLayerException, IOException, URISyntaxException
    {
        
   this.musicFilePath = musicFilePath;
   
   is = this.getClass().getResourceAsStream( musicFilePath );
        
   totalSongLength =  is.available();
   
    player = new Player( is );
    
        new Thread()
        {
            @Override
            public void run()
            {
                try 
                {
                    player.play();
                    
                    if( player.isComplete() && repeat )
                    {
                    play( musicFilePath );
                    }
                    
                    
                }
                catch ( JavaLayerException | IOException ex) 
                {
                    System.err.println("::: there was an error to play " + musicFilePath );
                } catch (URISyntaxException ex) {
                    Logger.getLogger(MusicPlayer.class.getName()).log(Level.SEVERE, null, ex);
                } 
            }////
        }.start();///
    
    }//
    
    /**
     * use this method to remuse current paused song
     * @throws FileNotFoundException
     * @throws JavaLayerException
     * @throws IOException 
     * @throws java.net.URISyntaxException 
     */
    public void resume( ) throws FileNotFoundException, JavaLayerException, IOException, URISyntaxException
    {
    
        paused = false;
        
    is = this.getClass().getResourceAsStream( musicFilePath );
    
    is.skip( totalSongLength - pauseLocation );
    
    player = new Player( is );
    
        new Thread()
        {
            @Override
            public void run()
            {
                try 
                {
                    player.play();
                }
                catch (JavaLayerException ex) 
                {
                    System.err.println("::: there was an error to play " + musicFilePath );
                }
            }////
        }.start();///
    
    }//
    
    
    
    /**
     * use this method to stop current song that is being 
     * played
     */
    public void stop()
    {
    paused = false;
        
        if( null != player)
        {
        player.close();
        
        totalSongLength = 0;
        pauseLocation = 0;
        }///
        
    }//
    
    /**
     * use this method to pause current played song
     */
    public void pause()
    {
    
        paused = true;
        if( null != player)
        {
            try 
            {
                pauseLocation = is.available();
                player.close();
            } 
            catch (IOException ex) 
            {
                System.out.println("::: error when song is paused");
            }
        
        }///
        
    }//

    /**
     * 
     * @return true if the song i will start once is done,
     * false if not
     */
    public boolean isRepeat() {
        return repeat;
    }

    /**
     * set if the song will start once is done
     * @param repeat 
     */
    public void setRepeat(boolean repeat) {
        this.repeat = repeat;
    }

    public boolean isPaused() {
        return paused;
    }

    public void setPaused(boolean paused) {
        this.paused = paused;
    }
    
}//class


I heard there are licensing issues with using MP3s in Java applications, and hence I always use OGG. I don’t know what they are though, could someone explain me about them?

Probably to do with the patents, but they’ve now expired anyway. https://en.wikipedia.org/wiki/MP3#Licensing.2C_ownership_and_legislation

i wasnt much aware of legal issues, but that is something to have in mind, I will check whether the patents are deprecated or not.
tnx!.

Is it okay to put a related wish-list item here?

I’d like to see OGG and MP3 decoders that give us the decompressed file back and let us handle the SourceDataLine for the final playback step. By doing just one less thing, it would allow us to get at the data for all sorts of effects, including varying the speed of playback or echo/chorus/distortion/filtering.

I gave a read on the licensing of MP3, and I got some quotes from the following links:


http://www.audioblog.iis.fraunhofer.com/mp3-software-patents-licenses/

This announcement only means that the licensing of MP3 software ends, and they aren’t required to pay to the Fraunhofer institute to use MP3 in their products. One important part is this:

The licensing program has of course been ended, but still there is a small catch. From this quote:

They aren’t saying that the MP3 software is now license free, you still have to get in touch with the company directly with your queries. It’s only that from now on, they won’t collect any fee, but there might be restrictions on the use of the software.

MP3 has got some patents, and as I’m aware, they’re in the European union and in the US. The patents in Europe were already expired in 2012, while since the US had patents for much longer time, they expired in the US in 2017. This means only that the software is patent free, and patents are much different from licenses and copyrights.

But having all this very sensitive stuff, and also that there are even better formats available, I think switching to either AAC or OGG Vorbis (there is also a term Theora I didn’t know about) is a much better option.

Except that this thread is about JLayer so Fraunhofer’s software isn’t relevant.

Correct, build your own MP3 decoder with out any license issues, use their software if you like but with their restrictions.

Personally I would go with ogg or opus just because they are far more superior formats

Hi

Why not using Paul Lamb’s 3D Sound System? Even Minecraft uses it. It supports both JavaSound and several Java bindings to the OpenAL API. I have used it with JOAL for years. It supports OGG very well, Midi, WAV, …

you’re so predictable! :stuck_out_tongue: Yes, if its features match what you need and you’re using OpenAL (the JavaSound backend is crap) then it might be an option.

Why do you claim that the JavaSound backend is crap? Why don’t you send your “constructive” remarks to the author of this library?

I had to install Mint and Mageia on several computers and the sound didn’t work when I ran “Breaking the Tower”. I assume that it’s my fault again as usual, I can’t blame JavaSound according to you. It’s really ridiculous, it doesn’t work on different hardware with two very different distributions and I’m sure that you’ll tell me again that the problem doesn’t come from JavaSound. As I’m honest, I’ll try this fix and I’ll make you know if it works:
https://keithp.com/blogs/Java-Sound-on-Linux/

I have, multiple times, years ago. Simply put, any sound library that doesn’t do its own mixing to output to the soundcard is built wrongly! (nb. the OpenAL software libraries do this for you on top of the soundcard driver, JavaSound just gives you direct access to the soundcard device)

It’s not your fault. It’s people writing JavaSound code that assumes because it works on one setup, it’ll work on all. JavaSound isn’t actually written like that - it doesn’t hide underlying platform differences, but gives you an API to query them. This is actually a good thing (eg. consider File vs nio2!).

It means that I’ll have to rewrite the source code using JavaSound in many cases.