r/javahelp • • Jan 12 '15

Playing a simple .mp3 file in this language is one of the hardest things I've ever tried to do.

Sorry if my vocabulary is not accurate. My idea is to have something like this:

..... Static List<String> fileNames = new ArrayList<String>(); .. Other fancy stuff Int I; ..

Public static void main(String[] args){ playSound(fileNames[i]); ..do other stuff.. playSound(fileNames[i+1]); }

Where playSound(); is a command to play the sound of a given String, which in this case comes from the Array list. Does that make sense?

2 Upvotes

20 comments sorted by

3

u/spdqbr Jan 12 '15 edited Jan 12 '15

Natively* it's going to be a bit of a bear, but you might check out JLayer. Even though it's old, it still works. Using JLayer, playing an mp3 was as simple as this for me just now:

import java.io.FileInputStream;
import javazoom.jl.player.Player;

class Test{
	public static void main(String[] args) throws Exception{
		Player player = new Player(new FileInputStream("c:\\temp\\Fire.mp3"));
		player.play();
	}
}

* Meaning from scratch

1

u/footballa Jan 12 '15

How can I make this into a void so I can run multiple sounds after a given input? I want to make an array list of sound files then just reference them when need be. I usually get an error about referencing non static element in a static environment

3

u/spdqbr Jan 12 '15

Not sure I follow what you mean with "Make this into a void." The error about referencing non static element in a static environment is probably unrelated to playing the actually mp3, and has to do with variable scoping. Without seeing your code it's tough to say, but I'm guessing you have something like this:

class Test{
    List<String> fileNames = new ArrayList<String>();

    public static void main(String[] args){
        fileNames.add("my.mp3");
    }
}

The method you're referencing "fileNames" from is static, but fileNames is not a static field. The simple fix in this case would be

class Test{
    static List<String> fileNames = new ArrayList<String>();

    public static void main(String[] args){
        fileNames.add("my.mp3");
    }
}

But most likely, depending on what you're doing, that's not going to be the best solution. It would help to see the code.

2

u/footballa Jan 12 '15

Sorry if my vocabulary is not accurate. My idea is to have something like this:

..... Static List<String> fileNames = new ArrayList<String>(); .. Other fancy stuff Int I; ..

Public static void main(String[] args){ playSound(fileNames[i]); ..do other stuff.. playSound(fileNames[i+1]); }

Does that make sense?

3

u/spdqbr Jan 12 '15

Ah, you want to put the player in its own method. You should be able to do this:

public static void playMp3File(String fileName){
	try{
		Player player = new Player(new FileInputStream(fileName));
		player.play();
	}catch(Exception e){
		e.printStackTrace();
	}
}

Which you could then call from elsewhere like this:

public static void main(String[] args){
    List<String> fileNames = new ArrayList<>(

	fileNames.add("C:\\temp\\foo.mp3");
	fileNames.add("C:\\temp\\bar.mp3");
	
	playMp3File(fileNames.get(0));
	playMp3File(fileNames.get(1));
}

Granted, this is a very basic stub with no error handling, no checking of the files, and it will block the program until the mp3 is done playing.

2

u/footballa Jan 12 '15

At this point I'll take anything that works. I'll try it tomorrow after I get some sleep. Thanks so much for the help, You're really good at this.

2

u/footballa Jan 12 '15

IT WORKS!!! Thank you!!! Wow. the second I heard the music I was very excited. thanks!

2

u/xela321 Professional Java Developer Jan 12 '15

Yeah, Java's support for this is not great. JMF is supposed to be able to do this sort of thing. I've never seen anyone do it. Sorry I couldn't be more helpful.

-1

u/footballa Jan 12 '15

I have never struggled to do something that sounds so simple in my whole life. This is almost as hard as getting a 5 seconds wait command going. I ended up just running a loop for 5 seconds using system.timeinmilliseconds();

I will not be returning to this language in the future, I'm sad to say

4

u/spdqbr Jan 12 '15

Since I'm in here anyway, this is the sleep method I keep around in for the cases I need something to sleep:

public static void sleep(long millis){
	long end = System.currentTimeMillis() + millis;
	
	do{
		try{
			Thread.sleep(end - System.currentTimeMillis());
		}catch(InterruptedException e){
			//do nothing
		}
	}while(System.currentTimeMillis() < end);
}

Should be less cpu intensive than just running an empty loop.

2

u/Darksonn Jan 12 '15

Any reason that

Thread.sleep(millis);

does not work?

1

u/spdqbr Jan 12 '15

Most of the time Thread.sleep(millis) will work just fine. Thread.sleep can be interrupted with thread.interrupt() . The above method guarantees the thread will block for at least the given number of milliseconds, even if interrupted. Example:

public static void main(String[] args) throws Exception{
	Runnable r1 = new Runnable(){
		public void run(){
			System.out.println(String.format("%s : %s will sleep for 5000 millis", 
					new Date().toString(), 
					Thread.currentThread().getName()));
			long start = System.currentTimeMillis();
			sleep(5000);
			System.out.println(String.format("%s : %s slept for %d millis", 
					new Date().toString(), 
					Thread.currentThread().getName(), 
					System.currentTimeMillis()-start));
		}
	};
	
	Runnable r2 = new Runnable(){
		public void run(){
			System.out.println(String.format("%s : %s will sleep for 5000 millis", 
					new Date().toString(), 
					Thread.currentThread().getName()));
			long start = System.currentTimeMillis();
			try{
				Thread.sleep(5000);
			}catch(InterruptedException e){
				//Do nothing
			}
			System.out.println(String.format("%s : %s slept for %d millis", 
					new Date().toString(), 
					Thread.currentThread().getName(), 
					System.currentTimeMillis()-start));
		}
	};
	
	Thread t1 = new Thread(r1, "Thread1");
	Thread t2 = new Thread(r2, "Thread2");
	
	t1.start();
	t2.start();
	
	sleep(3000);
	t1.interrupt();
	t2.interrupt();
}

Thread 1 uses the sleep method above, Thread 2 uses Thread.sleep. This outputs:

Mon Jan 12 09:31:31 MST 2015 : Thread1 will sleep for 5000 millis
Mon Jan 12 09:31:31 MST 2015 : Thread2 will sleep for 5000 millis
Mon Jan 12 09:31:34 MST 2015 : Thread2 slept for 2979 millis
Mon Jan 12 09:31:36 MST 2015 : Thread1 slept for 5001 millis

Essentially it prevents you (or anything else) from cancelling the sleep (either intentionally or unintentionally). Granted if you want the option to intentionally cancel the sleep, that could be included, but I still wouldn't rely on just Thread.sleep, since there is no way to guarantee you'll ever sleep for the full amount of time.

1

u/PatheticEarthling Jan 13 '15

First off, I'd say that maybe you're not cut out for programming if sleeping for 5 seconds is difficult for you, especially given you can find the answer in about 5 seconds from a google search.

But for everyone still suggesting Thread.sleep() in this day and age, I find this to be much better:

TimeUnit.SECONDS.sleep(5);

0

u/asking_science Master Brewer Jan 12 '15

I'm sad to say, but you sound like you are throwing a bit of a tantrum. Good luck with whatever other language you choose, I hope that you'll be able to code that full featured MP3 player in a single line of code.

2

u/lelarentaka Jan 12 '15

How hard can it be? You only have to open the file, verify that it contains MP3, parse the header, navigate to the start of the actual music, allocate a buffer, decode the MP3 into waveform, connect to the OS sound system, then pass the buffer to the native code.

Easy.

1

u/asking_science Master Brewer Jan 12 '15

...which pretty much applies to any type of media, not only mp3, or even audio.

5

u/asking_science Master Brewer Jan 12 '15

Oracle's MP3 plugin works well.

1

u/Philboyd_Studge Jan 12 '15

Are you using JavaFX?

0

u/footballa Jan 12 '15

I downloaded it but have no idea how to implement it

1

u/Philboyd_Studge Jan 12 '15

It's not easy, that's for sure.