Error playing music in Java program - java

Ok, so today I finally decided to ask what the issue was with my Java program after various attempts to fix it. If you didn't read the title, here is my issue: I'm trying to play music in a program, but it returns an error.
So first, I have to put the most important part; the class
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class Runawaytrain {
public void play() {
try {
AudioInputStream in = AudioSystem.getAudioInputStream(new File("hard1.wav"));
Clip clip = AudioSystem.getClip();
clip.open(in);
clip.start();
Thread.sleep(clip.getMicrosecondLength());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args){
new Runawaytrain().play();
}
}
This program I actually used as a test, since the music I was using in a game I'm co-creating wouldn't play. So when I made this program, I got the same stack trace:
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1189)
at krap2.Runawaytrain.play(Runawaytrain.java:12)
at krap2.Runawaytrain.main(Runawaytrain.java:22)
The file hard1.wav is included in my project directory. For some reason, it won't play however, and keeps returning that stack trace.
But I found something pretty odd about my program; when I use music from a URL, it works. So I tried inserting a URL using the file:// protocol, but still no luck.
So anyway, to finish this off, I'll put some info that may help in answering the question:
• OS: Mac
• JVM installed: 1.8.0
• Music source: Originally an MP3 file, converted through VLC into a .wav format
Thanks

I'm pretty sure you need to put the entire system path of the file when making the new File() (so on a Windows it would be "Users/username/.../hard1.wav" or whatever it would be on a Mac).

Related

What is ImageIO doing when reading a file?

I am a bit confused by ImageIO.read(file). When I try to read a .png file into a BufferedImage, at least on macOS, the focus moves to a new application named after my main class. It appears in the Menu bar. It does so even when I run java from the command line.
The annoying thing is that it moves the focus out of my IDE and I have to return to it manually.
I looked at the source of ImageIO.read(file). I discovered that it is calling ImageIO.createImageInputStream(file) and that is what triggers this behaviour.
My question is: what is ImageIO doing actually, why is my main class showing in the Menu bar when it is just loading information in memory. And most important, how can I avoid it?
Below the code to show the problem. Use any .png to test it.
package misc;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import java.io.File;
import java.io.IOException;
public class ReadImageTest {
public static void main(String[] args) {
try {
File file = new File("out/production/resources/picture.png");
long time = System.currentTimeMillis();
ImageInputStream stream = ImageIO.createImageInputStream(file);
long delay = System.currentTimeMillis() - time;
System.out.println("stream: " + stream.length());
System.out.println("time: " + delay/1000.0);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Using Headless Mode in the Java SE Platform describes what is headless mode and how to use it properly.
Headless mode is a system configuration in which the display device,
keyboard, or mouse is lacking. Sounds unexpected, but actually you can
perform different operations in this mode, even with graphic data.
You can enable it by adding below option to your program:
-Djava.awt.headless=true
See also:
What is the benefit of setting java.awt.headless=true?
How can I prevent command line java processes from stealing focus in OSX?
Setting java.awt.headless=true programmatically

AudioInputStream: Pop noise with Java 1.7 and 1.8 on macOS and 8-bit wav files

I have a weird problem with playing samples using AudioInputStream.
Three scenarios:
macOS, java 1.6: works perfectly
win, java 1.8: works perfectly
macOS, java 1.8: heavy pop sounds
The code I created for testing is straight forward. The sample is clean (zero cross at start and end). The first pop occurs already on soundLine.start() which is completely independent on the sample. The last pop occurs on soundLine.close() where the sample has been finished since couple of seconds. I added some delay to the code so it is easy to recognize on which place the code is.
I created demo videos where you can hear what happens:
on macOS Sierra (tested on a MBP and an iMac. First run with Java-8, second with Java-6. You can see the used java version on the screen):
https://youtu.be/bROPZq_33ME
on win (win7 running in Parallels): https://youtu.be/PGd4iW3oO4Y
As you can see (hear) the only problem is Java 1.8 under macOS. I also tested java 1.7 with the same result. Only on 1.6 the playback is correct.
The pop sound sounds strange because the sound has been recorded with the internal micro of my MBP. It is a typical pop sound you can hear when switching power on/off of a bad designed amplifier.
ADDENDUM: the problem seems to occur with 8-bit wav files only. 16 bit works fine.
ADDENDUM: in the mean time listed as bug: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8172164
Can anyone reproduce the problem? Any idea what's the reason? I currently assume a bug in Java.
import java.io.File;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
public class Soundtest
{
protected File sample=new File("user1.wav");
public Soundtest()
{
SourceDataLine soundLine = null;
int BUFFER_SIZE = 1024;
System.out.println("AudioInputStream test with "+System.getProperty("java.version")+" on "+System.getProperty("os.name"));
// Set up an audio input stream piped from the sound file.
try
{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(sample);
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
//Soundline ist noch nicht angelegt -> angelegen.
if(soundLine==null)
{
soundLine = (SourceDataLine) AudioSystem.getLine(info);
soundLine.open(audioFormat);
soundLine.start();
}
System.out.println("Started");
Thread.sleep(2000);
System.out.println("Playing");
int nBytesRead = 0;
byte[] sampledData = new byte[BUFFER_SIZE];
while (nBytesRead != -1)
{
nBytesRead = audioInputStream.read(sampledData, 0, sampledData.length);
if (nBytesRead >= 0)
{
soundLine.write(sampledData, 0, nBytesRead);
}
}
Thread.sleep(2000);
System.out.println("Draining");
soundLine.drain();
Thread.sleep(2000);
System.out.println("Closing");
soundLine.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new Soundtest();
}
}
There's nothing wrong with your code that I can tell. I've ran it myself with Java 1.8.0_60 on macOS Sierra 10.12.2, and there were no popping sounds through my headset, nor was there popping when coming out of the Internal Speakers. The only reason I could think of right now is that for some reason Java 1.8 doesn't like the audio interface or medium you're using, if it's any different than the generic speakers on your Mac. It could even be possible that audio buffering was done differently in 1.8. Try raising the buffer size to prevent under-runs (which could be the cause of the popping).

MBROLA voices with FreeTTS - Windows

Using MBROLA voices in a Java program with FreeTTS...
I am working on a simple text-to-speech program in Java. I have decided to use FreeTTS, but the voices are not really what I was thinking, and I was looking to use a female voice anyway. So I started looking around, and decided that I would use MBROLA to change the voice of my text-to-speech program.
I read that "FreeTTS can use MBROLA voices", but I searched everywhere and couldn't find a clear guide how to set MBROLA up, and what files are needed to do so. There are many forums on MBROLA working alongside FreeTTS, however it also seems that none of the people have any idea what they are doing.
So the questions:
What files need to be downloaded?
Steps to include these into my program?
Simple FreeTTS example using MBROLA voices?
Answers to the questions above:
1. What files need to be downloaded?
FreeTTS with all the libraries (freeTTS 1.2.2-bin) - download here
MBROLA zip folder mbr301d.zip
Voices which can be found on the MBROLA website
1.1 The FreeTTS libraries (found in freetts-1.2.2-bin/freetts-1.2/lib):
cmu_time_awb.jar
cmu_us_kal.jar
cmudict04.jar
cmulex.jar
cmutimelex.jar
en_us.jar
freetts.jar
freetts-jsapi10.jar
mbrola.jar
1.2 The MBROLA zip folder will include:
mbrola.exe
mbr302a (folder)
readme.txt
1.3 The Voices are zipped folders that include a single folder named 'us1' or 'af1' etc.
2. Steps to include these into my program?
NOTE: I had the MBROLA Tooklit installed on my computer too, however I am unsure whether it has an impact on the program, but I suspect that it doesn't. EDIT: I have tested to see whether the MBROLA toolkit is needed to run MBROLA alongside FreeTTS, and it turns out that it is not needed.
Extract freetts-1.2.2-bin
Copy the libraries to your project and include in build path
Unzip the mbr301d.zip folder
Rename 'mbr301d' to 'mbrola'
Unzip the voices to the folder you named 'mbrola'
After this is done, your mbrola folder should look like this:
[mbr302a] - folder
[us1] - folder (name depends on the language you downloaded)
mbrola.exe - file
readme.txt - file
You can place all your languages in this folder, and they will just be called from your Java program.
3. Simple FreeTTS example using MBROLA voices?
I've seen many people get this error:
System property "mbrola.base" is undefined. Will not use MBROLA voices.
The mbrola.base refers to where your mbrola files are located on your computer, and without the property being pointed to the correct location, you will recieve this error.
To NON-MBROLA users who get this error: Simply remove the mbrola.jar from your referenced libraries if you're only using FreeTTS
To set the mbrola.base property, use:
System.setProperty("mbrola.base", "C:/Path/to/your/mbrola")
Below is a simple Example to use the MBROLA voices in your FreeTTS program. Note that the steps above must be done before this will work. Simply changing the name of the voice to "mbrola_us1" will not work if the base isn't set!
package com.madmob.test;
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
public class TestTTS {
VoiceManager freettsVM;
Voice freettsVoice;
public TestTTS(String words) {
// Most important part!
System.setProperty("mbrola.base", "C:/mbrola");
freettsVM = VoiceManager.getInstance();
// Simply change to MBROLA voice
freettsVoice = freettsVM.getVoice("mbrola_us1");
// Allocate your chosen voice
freettsVoice.allocate();
sayWords(words);
}
public void sayWords(String words) {
// Make her speak!
freettsVoice.speak(words);
}
public static void main(String [] args) {
new TestTTS("Hello there! Now M BROLA and Free T T S work together!");
}
}
MBROLA and FreeTTS should now be working together! This code was copied right from my computer and has been tested before putting it down here.
Thanks to responses on this forum, I was finally able to make it working.
On windows 10; I carried out following steps to make it working:
Download freeTTS libraries and include them in my Java project in eclipse.
Download mbr301d.zip, extract it in a folder named mbrola within my project
Download mbrola database for us1, us2, us3 and en1 from http://www.tcts.fpms.ac.be/synthesis/mbrola/mbrcopybin.html
extract the voice DB zips downloaded in previous step directly in mbrola folder - don't change names of the folders.
include following code pieces to use it:
System.setProperty("mbrola.base", "ABSOLUTE_PATH_TO_mbrola_directory_ending_with_/");
voiceManager = VoiceManager.getInstance();
voice = voiceManager.getVoice("mbrola_us1");
Note: if your voice DB folder name is us1; then you should add it above as "mbrola_us1"; if it is en1, then it should be "mbrola_en1". This actually has done the trick for me.
Please find working example from here:
https://github.com/sunrise-projects/sphinx4/tree/glass
package com.sunriseprojects.freetts.demo;
import java.beans.PropertyVetoException;
import java.util.Locale;
import javax.speech.AudioException;
import javax.speech.Central;
import javax.speech.EngineException;
import javax.speech.EngineStateError;
import javax.speech.synthesis.Synthesizer;
import javax.speech.synthesis.SynthesizerModeDesc;
import javax.speech.synthesis.Voice;
public class SpeechUtils {
SynthesizerModeDesc desc;
Synthesizer synthesizer;
Voice voice;
public void init(String voiceName) throws EngineException, AudioException,
EngineStateError, PropertyVetoException {
if (desc == null) {
//default
// System.setProperty("freetts.voices",
// "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory");
//have to be setup
System.setProperty("freetts.voices",
"de.dfki.lt.freetts.en.us.MbrolaVoiceDirectory");
desc = new SynthesizerModeDesc(Locale.US);
Central.registerEngineCentral("com.sun.speech.freetts.jsapi.FreeTTSEngineCentral");
synthesizer = Central.createSynthesizer(desc);
synthesizer.allocate();
synthesizer.resume();
SynthesizerModeDesc smd = (SynthesizerModeDesc) synthesizer
.getEngineModeDesc();
Voice[] voices = smd.getVoices();
Voice voice = null;
for (int i = 0; i < voices.length; i++) {
if (voices[i].getName().equals(voiceName)) {
voice = voices[i];
break;
}
}
synthesizer.getSynthesizerProperties().setVoice(voice);
}
}
public void terminate() throws EngineException, EngineStateError {
synthesizer.deallocate();
}
public void doSpeak(String speakText) throws EngineException,
AudioException, IllegalArgumentException, InterruptedException {
synthesizer.speakPlainText(speakText, null);
synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);
}
public static void main(String[] args) throws Exception {
System.setProperty("mbrola.base", "C:\\lnx1\\home\\ggon\\git-projects\\mbrola");
SpeechUtils su = new SpeechUtils();
//have to be setup on your env
su.init("mbrola_us1");
//default
//su.init("kevin16");
//su.init("kevin");
//su.doSpeak("Hello world!");
su.doSpeak(SAMPLE);
su.terminate();
}
final static String SAMPLE = "Wiki said, Floyd Mayweather, Jr. is an American professional boxer. He is currently undefeated as a professional and is a five-division world champion, having won ten world titles and the lineal championship in four different weight classes";
}

how do I play a wave (wav) file in java

I've looked around on stack overflow, and a few other sites, but I can't really find anything helpful. I need to have code that can play an audio file that is inside the same as my Class.java file. In other words, I need it to play a file without typing in the exact location of the file, llike if I was sending it to a friend. Here is what I have:
import java.applet.*;
import java.net.*;
public class MainClass extends Applet {
public void init() {
try {
AudioClip clip = Applet.newAudioClip(
new URL(“file://C:/sound.wav”));
clip.play();
} catch (MalformedURLException murle) {
murle.printStackTrace();
}
}
But I can't get it to play from just anywhere, only that specific folder. Is there a way to do this without typing "URL" before the file location?
Change your URL declaration , change "file://C:/sound.wav" to "file:C:/sound.wav"
import java.applet.*;
import java.net.*;
public class MainClass {
public static void main(String[] args) {
try {
AudioClip clip = Applet.newAudioClip(
new URL("file:C:/sound.wav"));
clip.play();
} catch (MalformedURLException murle) {
murle.printStackTrace();
}}}
*I had tested it and working great under NetBeans IDE
I believe Applet.audioClip() is intended for use inside Applets, rather than a desktop app. One of the limitations is that you can only use a URL to locate the sound resource. On the other hand the Java Sound API is more versatile. It allows you to locate the sound resource with a File object as well as many other options.
You also need to figure out how to refer to your file. In particular, if you want to use a relative path, you need to figure out what base path your environment will start from. Embedding resources (images, sound bits, etc) into a Java project then use those resources will give you more details about how to resolve this issue.

Java: CaptureDeviceManager#getDeviceList() is empty?

I am trying to print out all of the capture devices that are supported using the #getDeviceList() method in the CaptureDeviceManager class and the returned Vector has a size of 0.
Why is that? I have a webcam that works - so there should be at least one. I am running Mac OS X Lion - using JMF 2.1.1e.
Thanks!
CaptureDeviceManager.getDeviceList(Format format) does not detect devices. Instead it reads from the JMF registry which is the jmf.properties file. It searches for the jmf.properties file in the classpath.
If your JMF install has succeeded, then the classpath would have been configured to include all the relevant JMF jars and directories. The JMF install comes with a jmf.properties file included in the 'lib' folder under the JMF installation directory. This means the jmf.properties would be located by JMStudio and you would usually see the JMStudio application executing correctly. (If your JMF install is under 'C:\Program Files', then run as administrator to get around UAC)
When you create your own application to detect the devices, the problem you described above might occur. I have seen a few questions related to the same problem. This is because your application's classpath might be different and might not include the environment classpath. Check out your IDE's properties here. The problem is that CaptureDeviceManager cannot find the jmf.properties file because it is not there.
As you have found out correctly, you can copy the jmf.properties file from the JMF installation folder. It would contain the correct device list since JMF detects it during the install (Check it out just to make sure anyway).
If you want do device detection yourself, then create an empty jmf.properties file and put it somewhere in your classpath (it might throw a java.io.EOFException initially during execution but that's properly handled by the JMF classes). Then use the following code for detecting webcams...
import javax.media.*;
import java.util.*;
public static void main(String[] args) {
VFWAuto vfwObj = new VFWAuto();
Vector devices = CaptureDeviceManager.getDeviceList(null);
Enumeration deviceEnum = devices.elements();
System.out.println("Device count : " + devices.size());
while (deviceEnum.hasMoreElements()) {
CaptureDeviceInfo cdi = (CaptureDeviceInfo) deviceEnum.nextElement();
System.out.println("Device : " + cdi.getName());
}
}
The code for the VFWAuto class is given below. This is part of the JMStudio source code. You can get a good idea on how the devices are detected and recorded in the registry. Put both classes in the same package when you test. Disregard the main method in the VFWAuto class.
import com.sun.media.protocol.vfw.VFWCapture;
import java.util.*;
import javax.media.*;
public class VFWAuto {
public VFWAuto() {
Vector devices = (Vector) CaptureDeviceManager.getDeviceList(null).clone();
Enumeration enum = devices.elements();
while (enum.hasMoreElements()) {
CaptureDeviceInfo cdi = (CaptureDeviceInfo) enum.nextElement();
String name = cdi.getName();
if (name.startsWith("vfw:"))
CaptureDeviceManager.removeDevice(cdi);
}
int nDevices = 0;
for (int i = 0; i < 10; i++) {
String name = VFWCapture.capGetDriverDescriptionName(i);
if (name != null && name.length() > 1) {
System.err.println("Found device " + name);
System.err.println("Querying device. Please wait...");
com.sun.media.protocol.vfw.VFWSourceStream.autoDetect(i);
nDevices++;
}
}
}
public static void main(String [] args) {
VFWAuto a = new VFWAuto();
System.exit(0);
}
}
Assuming you are on a Windows platform and you have a working web-cam, then this code should detect the device and populate the jmf.properties file. On the next run you can also comment out the VFWAuto section and it's object references and you can see that CaptureDeviceManager reads from the jmf.properties file.
The VFWAuto class is part of jmf.jar. You can also see the DirectSoundAuto and JavaSoundAuto classes for detecting audio devices in the JMStudio sample source code. Try it out the same way as you did for VFWAuto.
My configuration was Windows 7 64 bit + JMF 2.1.1e windows performance pack + a web-cam.
I had the same issue and I solved by invoking flush() on my ObjectInputStream object.
According to the API documentation for ObjectInputStream's constructor:
The stream header containing the magic number and version number are read from the stream and verified. This method will block until the corresponding ObjectOutputStream has written and flushed the header.
This is a very important point to be aware of when trying to send objects in both directions over a socket because opening the streams in the wrong order will cause deadlock.
Consider for example what would happen if both client and server tried to construct an ObjectInputStream from a socket's input stream, prior to either constructing the corresponding ObjectOutputStream. The ObjectInputStream constructor on the client would block, waiting for the magic number and version number to arrive over the connection, while at the same time the ObjectInputStream constructor on the server side would also block for the same reason. Hence, deadlock.
Because of this, you should always make it a practice in your code to open the ObjectOutputStream and flush it first, before you open the ObjectInputStream. The ObjectOutputStream constructor will not block, and invoking flush() will force the magic number and version number to travel over the wire. If you follow this practice in both your client and server, you shouldn't have a problem with deadlock.
Credit goes to Tim Rohaly and his explanation here.
Before calling CaptureDeviceManager.getDeviceList(), the available devices must be loaded into the memory first.
You can do it manually by running JMFRegistry after installing JMF.
or do it programmatically with the help of the extension library FMJ (Free Media in Java). Here is the code:
import java.lang.reflect.Field;
import java.util.Vector;
import javax.media.*;
import javax.media.format.RGBFormat;
import net.sf.fmj.media.cdp.GlobalCaptureDevicePlugger;
public class FMJSandbox {
static {
System.setProperty("java.library.path", "D:/fmj-sf/native/win32-x86/");
try {
final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
sysPathsField.setAccessible(true);
sysPathsField.set(null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
GlobalCaptureDevicePlugger.addCaptureDevices();
Vector deviceInfo = CaptureDeviceManager.getDeviceList(new RGBFormat());
System.out.println(deviceInfo.size());
for (Object obj : deviceInfo ) {
System.out.println(obj);
}
}
}
Here is the output:
USB2.0 Camera : civil:\\?\usb#vid_5986&pid_02d3&mi_00#7&584a19f&0&0000#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\global
RGB, -1-bit, Masks=-1:-1:-1, PixelStride=-1, LineStride=-1

Categories