JavaFX audio doesn't seem to be playing - java

I am fairly new to JavaFX and recently wanted to play audio with an MP3 file rather than WAV. From what I can tell, I am doing things correctly and I don't get any errors, but I also don't hear any sound.
I will post the parts of my code that matter below. If I'm missing something please let me know. Thanks.
try {
URL sound = getClass().getResource("/resources/origin.mp3");
Media hit = new Media(sound.toExternalForm());
musicPlayer = new MediaPlayer(hit);
musicPlayer.setVolume(1.0);
}
catch(Exception e) {
System.out.println("whoops: " + e);
}
checkMusic();
Check Music Method:
public void checkMusic() {
if(music)
musicPlayer.setAutoPlay(true);
else
musicPlayer.stop();
}
I also tried just musicPlayer.play(); as well.
EDIT
And yes, I am sure the code within the if statement runs, I have checked it with println, and they print out. The music boolean is just a controller for settings in the program/game.

instead of
Media hit = new Media(sound.toExternalForm());
try this:
final Media media = new Media(sound.toString());

Related

Java picam preview

I am currently trying to incorporate a temporary stream in my card panel layed out like this.
Layout
Where it says scan your QRCode im trying to get a stream from the picam. Here is the issue.
I dont know how i can buffer that into the Java application
I got the command i want --> "raspistill -w 200 -h 200 -q 100 -t 5", but i just dont know how this would work. This is the first time im dealing with any video stream.
As for the second part. I need that "preview" to take a picture whenever it is able to grab the QRCode. I checked both apis for the raspberry pi camera but im still lost as in for direction. I also need this buffered so i can instantly parse it into my decodeQRCode method. What component do i need to accomplish this?
I decided to go with sarxos webcam api.
class VideoFeed extends Thread {
public void run() {
webcam.open();
boolean bool = true;
while (bool) {
try {
BufferedImage image = webcam.getImage();
var = BackEnd.refund(image,type[0]);
lblCamera.setIcon(new ImageIcon(image));
if (var[0] != null) {
bool = false;
webcam.close();
btnScan.doClick();
} else {
Thread.sleep(10);
}
} catch (InterruptedException ex) {
System.out.println("Error: " + ex);
}
}
}
}
started it by doing
new VideoFeed().start();
With this i opted for a more general driver.

JavaFX MediaPlayer highly inaccurate seeking

I'm using 320 kbps roughly 1 hour long MP3 files. The project I'm working on would seek in a collection of music inside an MP3 file so that it can shuffle the songs. I would give the timestamps to the program and it would seek to the song. It would work if JavaFX's seek method wasn't highly inaccurate.
After using MediaPlayer.seek(duration) The MediaPlayer.getCurrentTime() returns the duration we seeked to as expected. However if we listen to the mp3 file(either without seeking or in an external mp3 player) we realize that the time reported and reality is very different, sometimes even seconds.
For example MediaPlayer.seek(Duration.millis(2000)) results seeking to 0 seconds. A 2 second failure rate is not acceptable.
With WAV it seems to work. Though it does not with MP3.
The two workarounds I think so far are possible:
Writing an MP3 Decoder and Player which doesn't have the bug
Using uncompressed WAV files
Does anyone know anything better?
If anyone needs the source code there isn't much more in it:
public static void main(String[] args) {
MediaPlayer player = null;
JFXPanel fxPanel = new JFXPanel(); //To initialize JavaFX
try {
String url = new File("E:\\Music\\test.mp3").toURI().toURL().toExternalForm();
player = new MediaPlayer(new Media(url));
System.out.println("File loaded!");
} catch (MalformedURLException e) {
//e.printStackTrace();
System.out.println("Error with filename!");
System.exit(0);
}
player.play();
System.out.println("Playing!");
while (true)
{
Scanner reader = new Scanner(System.in);
String string = reader.nextLine();
if (string.equals("Exit")) System.exit(0);
else if (string.equals("Seek"))
{
player.seek(Duration.millis(2000)); //this seeks to the beggining of the file
player.pause();
try {
Thread.sleep(100); //player.getCurrentTime() doesn't update immediately
} catch (InterruptedException e) { }
System.out.println("Time: " + player.getCurrentTime().toMillis() + " / " + player.getTotalDuration().toMillis());
player.play();
}
}
}
I would recommend using the javazoom library. It is an open source java library that already has this stuff written without errors(At least none that I found).
Source
http://www.javazoom.net/index.shtml
Place your call to the seek method off the UI thread or your UI will hang.
new Thread(() ->player.seek(Duration.millis(2000))).start();

disable other sounds in java

I wrote a program in Java using the pi4j lib to make sound whenever a (physical) button is clicked. This program works, but it now plays all the sounds interchangeably. I want that when you click on 2,3,4 or more buttons you only hear one sound.
This is the code I hope you can help.
public class ButtonSoundsProject{
public static void main(String args[]) throws InterruptedException {
System.out.println("Toy has been started!");
// create gpio controller
final GpioController gpio = GpioFactory.getInstance();
// provision gpio pin #02 as an input pin with its internal pull down resistor enabled
GpioPinDigitalInput[] pins = {
gpio.provisionDigitalInputPin(RaspiPin.GPIO_00, PinPullResistance.PULL_DOWN),
gpio.provisionDigitalInputPin(RaspiPin.GPIO_01, PinPullResistance.PULL_DOWN),
gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, PinPullResistance.PULL_DOWN),
gpio.provisionDigitalInputPin(RaspiPin.GPIO_03, PinPullResistance.PULL_DOWN),
gpio.provisionDigitalInputPin(RaspiPin.GPIO_04, PinPullResistance.PULL_DOWN),
gpio.provisionDigitalInputPin(RaspiPin.GPIO_05, PinPullResistance.PULL_DOWN),};
final ArrayList<String> soundList = new ArrayList<String>();
soundList.add("/home/pi/Sounds/Sound1.wav");
soundList.add("/home/pi/Sounds/Sound2.wav");
soundList.add("/home/pi/Sounds/Sound3.wav");
soundList.add("/home/pi/Sounds/Sound4.wav");
soundList.add("/home/pi/Sounds/Sound5.wav");
soundList.add("/home/pi/Sounds/Sound6.wav");
soundList.add("/home/pi/Sounds/Sound7.wav");
soundList.add("/home/pi/Sounds/Sound8.wav");
soundList.add("/home/pi/Sounds/Sound9.wav");
soundList.add("/home/pi/Sounds/Sound10.wav");
soundList.add("/home/pi/Sounds/Sound11.wav");
soundList.add("/home/pi/Sounds/Sound12.wav");
// create and register gpio pin listener
GpioPinListenerDigital listener = new GpioPinListenerDigital() {
#Override
public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
// display pin state on console
final int randomNum = 0 + (int) (Math.random() * 12);
System.out.println(randomNum);
System.out.println(" --> GPIO PIN STATE CHANGE: " + event.getPin() + " = " + event.getState());
InputStream in;
try {
System.out.println(soundList.get(randomNum).toString());
String filepath = soundList.get(randomNum).toString();
in = new FileInputStream(new File(filepath));
AudioStream as = new AudioStream(in);
AudioPlayer.player.start(as);
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
gpio.addListener(listener, pins);
for (;;) {
Thread.sleep(500);
}
}
}
As stated in the comments, I can't give you advise regarding the AudioStream and AudioPlayer classes because I don't seem to have those in my JDK. Since my method is similar, I'll give you what I have, and you can hopefully take it from there.
Basically, the solution is to stop and/or "mute" that audio clip. This is how I accomplish it using the javax.sound package.:
private Clip currentAudioClip; // Keep a reference to the current clip being played
public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
// Call this every time regardless.
// If nothing is playing, this will do nothing.
stopAudio();
String filepath = soundList.get(randomNum)
URL soundFileUrl = new File(filePath).toURI().toURL();
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundFileUrl);
Line.Info lineInfo = new Line.Info(Clip.class);
Line line = AudioSystem.getLine(lineInfo);
currentAudioClip = (Clip) line;
currentAudioClip.open(audioInputStream);
audioClip.start();
// Alternative if you want to loop continuously. Comment out the `.start` line to use this.
// audioClip.loop(Clip.LOOP_CONTINUOUSLY);
}
public void stopAudio(){
if(audioClip != null){
muteLine(); // A gotcha I discovered (see explanation below)
audioClip.stop();
// audioClip.loop(0); // if you chose to loop, use this instead of `.stop()`
audioClip.flush();
audioClip = null;
}
}
public void muteLine(){
BooleanControl muteControl = (BooleanControl) audioClip.getControl(BooleanControl.Type.MUTE);
if(muteControl != null){
muteControl.setValue(true); // True to mute the line, false to unmute
}
}
In short, every time a pin state change event is fired, the previous audio clip will be ceased, and a new one should play. You shouldn't get any sound overlapping with this.
Also note that this is a slight modification of my original code, so let me know if there are any issues
Note about the GOTCHA
I wrote a question over on the Raspberry PI Stackexchange about an odd problem I encountered. The problem was that I discovered my audio clip would not cease playing on command. It would continue playing for a seemingly arbitrary amount of time. The stranger thing is that I only observed this while testing the app on the raspberry; it worked perfectly fine on my local machine (and even on several other machines).
It is possible my issue is related to the "looping" of my clip; if that is the case, and you simply want the clip to play for its length and no further, you may not encounter that issue, and you can probably dispense with the "muting" code I included. However, if you do observe the same issue, at least you have a solution.
Hope this helps, let me know if you have any questions.

Java VLCJ player, set audio track is not working

I am currently working on java media player that can play mkv format. I am using VLCJ, everything is working except when I try to change audio track which is not working.
here is the code
public class mediaplayer {
private static JFileChooser filechooser = new JFileChooser();
public mediaplayer() {
}
public static void main(String[] args) {
String vlcPath = "", mediaPath = "";
File ourfile;
filechooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
filechooser.showSaveDialog(null);
ourfile = filechooser.getSelectedFile();
mediaPath = ourfile.getAbsolutePath();
EmbeddedMediaPlayerComponent mediacom = new EmbeddedMediaPlayerComponent();
JFrame frame = new JFrame();
frame.setContentPane(mediacom);
frame.add(canvas);
frame.setLocation(100, 100);
frame.setSize(1050, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
MediaPlayer mplayer = mediacom.getMediaPlayer();
mplayer.playMedia(mediaPath);
mplayer.setAudioTrack(1);
}
}
In libVLC versions before vlc 2.0.5 the native API call to set the audio track was bugged.
With the fix in libVLC 2.0.5, setting the audio track works reliably but you can not just assume a simple index from 0..N and you can not assume sequential track numbers - you must enumerate the audio tracks by calling mediaPlayer.getAudioDescriptions(). The returned TrackDescription objects contain an audio track identifier that should be used with mediaPlayer.setAudioTrack().
To disable audio, you can select the audio track identifier of the track with a a description of "Disable".
Also be aware that you might not be able to set the audio track immediately after calling mediaPlayer.playMedia(). Media is started asynchronously and you may need to wait until the media has actually started and/or has been parsed before the track information is available.
6 years later
The API have grown a lot
If you want to stop or choose an audio track you can use this code snippet and adapt it, the idea is to wait for the player to start using a process then switching to what you need, in my case is the audio disabling
new Thread(
() -> {
try {
while(!empc.mediaPlayer().status().isPlaying())Thread.sleep(500);
empc.mediaPlayer().audio().trackDescriptions().stream()
.filter(td -> td.description().equals("Disable"))
.forEach(t -> empc.mediaPlayer().audio().setTrack(t.id()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
).start();
empc is my media player instance {the embed one for more precision in the player component}

Zxing qr scanning blackberry crash

I am implementing a QR code scanner for blackberry devices and I am using ZXing libraries to do so. This is for os 6+ by the way. The problem I am having is that sometimes, only sometimes, when the camera opens up to prepare scanning, the device will freeze and do a full reboot...
Otherwise it works most of the time, I am able to scan and decode the qr codes etc. However is just seems like it occasionally feels like crashing for no reason. I do not know if it is something with the camera or something in my code, but I will provide the code.
public void scanBarcode() {
// First we create a hashtable to hold all of the hints that we can
// give the API about how we want to scan a barcode to improve speed
// and accuracy.
Hashtable hints = new Hashtable();
// The first thing going in is a list of formats. We could look for
// more than one at a time, but it's much slower.
Vector formats = new Vector();
formats.addElement(BarcodeFormat.QR_CODE);
hints.put(DecodeHintType.POSSIBLE_FORMATS, formats);
// We will also use the "TRY_HARDER" flag to make sure we get an
// accurate scan
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
// We create a new decoder using those hints
BarcodeDecoder decoder = new BarcodeDecoder(hints);
// Finally we can create the actual scanner with a decoder and a
// listener that will handle the data stored in the barcode. We put
// that in our view screen to handle the display.
try {
_scanner = new BarcodeScanner(decoder, new MyBarcodeDecoderListener());
_barcodeScreen = new MyBarcodeScannerViewScreen(_scanner);
} catch (Exception e) {
return;
}
// If we get here, all the barcode scanning infrastructure should be set
// up, so all we have to do is start the scan and display the viewfinder
try {
_scanner.stopScan();
_scanner.getPlayer().start();
_scanner.startScan();
UiApplication.getUiApplication().pushScreen(_barcodeScreen);
} catch (Exception e) {
}
}
/***
* MyBarcodeDecoderListener
* <p>
* This BarcodeDecoverListener implementation tries to open any data encoded
* in a barcode in the browser.
*
* #author PBernhardt
*
**/
private class MyBarcodeDecoderListener implements BarcodeDecoderListener {
public void barcodeDecoded(final String rawText) {
//UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());
UtilityDecoder.saveToHistory(rawText);
try {
UtilityDecoder.distributeBarcode(rawText);
} catch (PIMException e) {
}
}
}
I basically call scanBarcode() when I click on a button on a toolbar.
Can anyone tell me if my code is the problem, or the device, or something else? Thanks in advance for any help provided!
Try this link:
Scan Any Type of Barcode Image which Supports Blackberry
See this forun link and see the discussions of that link. Surely, you will get overall concept of barcode scanning and you will also get the Implemention of QRCode in version 5.0
Any type of Barcode scaning in 5.0

Categories