jlayer.javazoom player can not stop mp3 - java

How to stop MP3 in jlayer? (the stop() is no longer used)
My code as follows:
//main class mp3_main
private AdvancedPlayer player;
public static void main(String[] args) {
String file="C:\\cd.mp3";
mp3PlayerSample mp3 = new mp3PlayerSample(file);
mp3.play();
mp3.stop();
}
//class mp3PlayerSample
private String filename;
private BufferedInputStream buffer;
private AdvancedPlayer player;
//constructor
public mp3PlayerSample(String filename)
{
this.filename = filename;
}
//start method
public void play()
{
FileInputStream fis;
try {
fis = new FileInputStream(this.filename);
buffer = new BufferedInputStream(fis);
try {
this.player=new AdvancedPlayer(buffer);
player.play();
} catch (JavaLayerException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//stop method
public void stop()
{
if(player != null){
player.close();
}
}

You need to run the player in its own thread, right now your main method blocks after calling play() until playback has completed.
Note, the classes Player/AdvancedPlayer included with jlayer are meant as example code to demonstrate how the decoding and output of decoded audio has to be wired up. They are not fully fledged players (e.g. there isn't even volume control).

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import java.util.Scanner;
class Music extends Thread{
public void run(){
try {
FileInputStream fileInputStream = new FileInputStream("Freedom.mp3");
Player player = new Player(fileInputStream);
player.play();
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(JavaLayerException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main (String[]args){
Scanner keyboard = new Scanner(System.in);
Music music = new Music();
music.start();
System.out.println("Stop music: ");
int off = keyboard.nextInt();
if(off == 0) {
music.stop();
}
}
}

Related

Cannot play the sound of music with no error for Java

I am trying to run the music that I have, but it does not work. There is no error showing up in the eclipse any more, but the sound is not played. This is my code that I have
public class Music extends Thread {
private Player player;
private boolean isLoop;
private File file;
private FileInputStream fis;
private BufferedInputStream bis;
public Music(String name, boolean isLoop)
{
try {
this.isLoop = isLoop;
//Find the link to the file and play, save the file to the buffer
file = new File(Main.class.getResource("/music/" + name).toURI());
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
player = new Player(bis);
} catch(Exception e){
System.out.println("No music");
}
}
//Get the time of the music, how long it is played
public int getTime() {
if(player == null)
{
return 0;
}
return player.getPosition();
}
//Stop the music played
public void close() {
isLoop = false;
player.close();
this.interrupt();
}
#Override
public void run() {
try {
player.play();
do {
player.play();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
player = new Player(bis);
} while(isLoop);
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
Also this my setting I have
Thank you for the help
Your problem starts here -> file = new File(Main.class.getResource("/music/" + name).toURI());
An embedded resource can't be reference as a File, because, well, it's not. Instead use Class#getResourceAsStream directly.
Next, you should avoid extending from Thread, thread's are not re-entrant, that is, once stopped, you can't restart them. Instead, implement Runnable, for example...
public class Music implements Runnable {
private String name;
private Player player;
private boolean isLoop;
private Thread playerThread;
public Music(String name, boolean isLoop) {
this.isLoop = isLoop;
this.name = name;
}
//Get the time of the music, how long it is played
public int getTime() {
if (player == null) {
return 0;
}
return player.getPosition();
}
//Stop the music played
public void stop() {
isLoop = false;
if (player == null) {
return;
}
player.close();
playerThread = null;
}
public void waitFor() throws InterruptedException {
if (playerThread == null) {
return;
}
playerThread.join();
}
public void play() throws InterruptedException {
if (playerThread != null) {
stop();
waitFor();
}
playerThread = new Thread(this);
playerThread.start();
}
protected void playAudio() throws IOException, JavaLayerException {
try (BufferedInputStream bis = new BufferedInputStream(getClass().getResourceAsStream("/music/" + name))) {
player = new Player(bis);
player.play();
}
}
#Override
public void run() {
try {
do {
System.out.println("Start playing");
playAudio();
System.out.println("All done");
} while (isLoop);
} catch (Exception e) {
e.printStackTrace();
}
stop();
}
}

Sound handler using Clip and AudioInputstream keeps audio in RAM

A sound handler I have developed for my game handles playing musing and sound effects. In theory there should be one voice for each sfx and music, and each should only be able to play one track at a time.
However, whilst monitoring the resources used the RAM used exponentially increases when skipping through tracks, all the way to the argument limit of 8Gb - meaning that it loads tracks into memory again each time it is played and is never dumped.
Whilst debugging this, I placed an unhealthy amount of .Drains and .Flushes on the Clips in my class, and resetting the AudioInputStream to null, experimenting with no effect.
On a side note, when skipping through tracks quickly, an occasional phantom voices will appear, continuing to play in the background uncontrollably of the controlled Music voice - I feel this are likely closely related.
Below is the entire class, including all positions which .Drain etc were used during debugging. Song skipping starts from NextTrack() or PrevTrack(), both give the same result.
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class SoundHandler {
private static Clip sfx = null, Music = null;
public static boolean MusicEnabled = true;
private static int STIndex = 0;
private static final int TrackCount = 41;
private static AudioInputStream audioInputStream;
//Channel true = sfx, else music
private static void PlayFile(String filename, boolean Chanel){
try {
audioInputStream = AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream(filename)));
if (Chanel) {
try {sfx.stop(); sfx.drain();}catch (Exception e) {}
sfx = AudioSystem.getClip();
sfx.open(audioInputStream);
sfx.start();
} else {
if (!MusicEnabled) {return;}
try {Music.stop(); Music.drain();}catch (Exception e) {}
Music = AudioSystem.getClip();
Music.open(audioInputStream);
Music.start();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
//Music Handler for external
private static void PlayTrack() {
String Location = String.valueOf(Game.ResourcePath + "/Audio/Runtime/ST" + STIndex + ".wav");
PlayFile(Location, false);
}
public static void SFX(String Effect) {
String Location = String.valueOf(Game.ResourcePath + "/Audio/Runtime/" + Effect + ".wav");
PlayFile(Location, true);
}
public static void NextTrack() {
if (STIndex >= TrackCount) {STIndex = 0;} else {STIndex++;}
Music.stop();
Music.drain();
Music.flush();
try {audioInputStream.close();} catch (IOException e) {}
audioInputStream = null;
PlayTrack();
}
public static void PrevTrack() {
if (STIndex <= 0) {STIndex = TrackCount;} else {STIndex--;}
Music.stop();
Music.drain();
Music.flush();
try {audioInputStream.close();} catch (IOException e) {}
audioInputStream = null;
PlayTrack();
}
public static void StartMusic () {
MusicEnabled = true;
STIndex = 0;
String Location = String.valueOf(Game.ResourcePath + "/Audio/Runtime/ST" + STIndex + ".wav");
PlayFile(Location, false);
}
public static void PlayIndex(int index) {
MusicEnabled = true;
STIndex = 0;
String Location = String.valueOf(Game.ResourcePath + "/Audio/Runtime/ST" + index + ".wav");
PlayFile(Location, false);
}
public static void PlayStop() {
MusicEnabled = !MusicEnabled;
if (MusicEnabled) {
StartMusic();
} else {
try {Music.stop(); Music.drain(); Music.flush();}catch (Exception e) {}
}}
public static void Tick() {
try {if ((!Music.isActive()) && MusicEnabled){NextTrack();}} catch (Exception e) {}
if (!MusicEnabled) {
try {if (!Music.isActive()){Music.stop(); Music.drain();}} catch (Exception e) {}
}}
public static int getST() {
return STIndex;
}
}

Java, javazoom program for playing MP3 files(AdvancedPlayer), event.getFrame() is giving random things

I'm trying to write a program that plays .mp3 files, playing them works perfectly. But pausing is causing some trouble. When I pause the song (stop the song and ask for the frame) I get an incorrect value.
class PauseStartMP3Test {
private static AdvancedPlayer player;
private static int pausedOnFrame = 0;
private static boolean playing = false;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(true) {
String s = in.next();
if(!s.equals("")) {
if(!playing) {
playing = true;
play();
}
else {
player.stop();
}
}
}
}
public static void play() {
File file = null;
file = new File("C:\\Users\\Remco\\Desktop\\Programming\\musictest/throughglass.mp3");
try {
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
player = new AdvancedPlayer(bis);
new Thread() {
public void run() {
try {
if(playing) {
player.setPlayBackListener(new PlaybackListener() {
#Override
public void playbackFinished(PlaybackEvent event) {
pausedOnFrame = event.getFrame();
System.out.println(pausedOnFrame);
playing = false;
}
});
player.play(pausedOnFrame, Integer.MAX_VALUE);
}
else {
player.stop();
}
}
catch (Exception e) {
System.out.println(e);
}
}
}.start();
} catch (JavaLayerException ex) {
System.out.println(ex);
}
} catch (FileNotFoundException ex) {
System.out.println(ex);
}
}

Java Detecting when sound stops

I have a sound class for my application and it plays a certain sound when I tell it too. I want to be able to detect when the sound is finished playing so I can then play a different sound without them over lapping here is my sound class:
public class Sound {
public static final Sound cash = new Sound("/cash.wav");
public static final Sound snap = new Sound("/snap.wav");
public static final Sound disarm = new Sound("/disarm.wav");
public static final Sound tp = new Sound("/tp.wav");
public static final Sound select = new Sound("/selectBTN.wav");
public static final Sound scroll = new Sound("/btn.wav");
public static final Sound fire = new Sound("/fire2.wav");
private AudioClip c;
public Sound(String filename) {
try {
c = Applet.newAudioClip(Sound.class.getResource(filename));
} catch (Exception e) {
e.printStackTrace();
}
}
public void play() {
try {
new Thread() {
public void run() {
if (!title.mute) {
c.play();
}
}
}.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
then to play the sound I use this line of code:
Sound.cash.play();
How can I detect when the sound is finished playing
Try something like this (is an aproximation), with LineListener to detect the end of playing:
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineEvent.Type;
import javax.sound.sampled.LineListener;
public class Sound {
private Clip c;
public Sound(final String filename) {
try {
c = AudioSystem.getClip();
final AudioInputStream inputStream = AudioSystem.getAudioInputStream(Sound.class.getResourceAsStream(filename));
c.open(inputStream);
c.addLineListener(new LineListener() {
#Override
public void update(final LineEvent event) {
if (event.getType().equals(Type.STOP)) {
System.out.println("Do something");
}
}
});
} catch (final Exception e) {
e.printStackTrace();
}
}
public void play() {
c.start();
}
public static void main(final String[] args) throws InterruptedException {
final Sound s = new Sound("/cash.wav");
s.play();
Thread.sleep(100000);
final Sound p = new Sound("/cash.wav");
p.play();
Thread.sleep(10000);
}
}

How can I add sound to a java program

I have been trying to write a basic 'Jeopardy' game in java, and right now I'm trying to add sound to play when the player get's an answer right or wrong. I have tried to add the sound (placing the sound file in the bin folder and using the code below), but when I try to play the file there is no sound. There is no null pointer exception.
public class Overview{
static AudioClip right, wrong;
//start the game
public static void guiApp(){
right = Applet.newAudioClip(Jeopardy.class.getResource("correct.wav"));
wrong = Applet.newAudioClip(Jeopardy.class.getResource("wrong.wav"));
right.play();
intro = new Intro();
intro.start();
}
public static void main (String[ ] args)
{
javax.swing.SwingUtilities.invokeLater (new Runnable ( )
{
public void run ( )
{
guiApp();
}
}
);
}
}
The following is essentially what is happening in the method called:
public class Intro{
public Intro(){
}
public void start(){
JFrame frame = new JFrame();
frame.setSize(100, 100);
frame.setVisible(true);
}
}
This is something that i use to play sound.
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;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
public class SoundPlayer extends Thread
{
private static final int BUFFER_SIZE = 128000;
private static File soundFile;
private static AudioInputStream audioStream;
private static AudioFormat audioFormat;
private static SourceDataLine sourceLine;
private String file;
public static String turn = "data/bell.wav"; //bell sound for black jack when it is your turn (played once each turn)
/**
* Plays the sound of the sent file name
* #param file Audio File's path
*/
public SoundPlayer(String file)
{
super("SoundPlayer");
this.file = file;
start();
}
public void run()
{
String strFilename = file;
try {
soundFile = new File(strFilename);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
try {
audioStream = AudioSystem.getAudioInputStream(soundFile);
} catch (Exception e){
e.printStackTrace();
System.exit(1);
}
audioFormat = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
try {
sourceLine = (SourceDataLine) AudioSystem.getLine(info);
sourceLine.open(audioFormat);
} catch (LineUnavailableException e) {
e.printStackTrace();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
sourceLine.start();
int nBytesRead = 0;
byte[] abData = new byte[BUFFER_SIZE];
while (nBytesRead != -1) {
try {
nBytesRead = audioStream.read(abData, 0, abData.length);
} catch (IOException e) {
e.printStackTrace();
}
if (nBytesRead >= 0) {
#SuppressWarnings("unused")
int nBytesWritten = sourceLine.write(abData, 0, nBytesRead);
}
}
sourceLine.drain();
sourceLine.close();
this.stop();
}
public static void main(String[] args)
{
}
}

Categories