getAudioInputStream causes an exception - java

I'm trying to make a very simple program to play a sound file.
So far all I have is:
import java.io.File;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class SoundTest {
public static void main(String[] args) {
File sound = new File("/home/pierce/Downloads/clapping.wav");
playSound(sound);
}
static void playSound(File sound) {
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(sound));
} catch(Exception e) {
System.out.println("Something failed");
}
}
}
After adding the line "clip.open(AudioSystem.getAudioInputStream(sound));", I started getting the message in the exception. Basically I have no idea why. Any help would be appreciated.
If it helps to see what I'm aiming at, I'm trying to follow this tutorial.
Thanks
Edit: Stack trace, as requested:
java.lang.IllegalArgumentException: Invalid format
at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.createStream(PulseAudioDataLine.java:142)
at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.open(PulseAudioDataLine.java:99)
at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.open(PulseAudioDataLine.java:283)
at org.classpath.icedtea.pulseaudio.PulseAudioClip.open(PulseAudioClip.java:402)
at org.classpath.icedtea.pulseaudio.PulseAudioClip.open(PulseAudioClip.java:453)
at SoundTest.playSound(SoundTest.java:17)
at SoundTest.main(SoundTest.java:10)

Related

Java beeping noise after Clip ends

I tried to play some sounds using the javax.sound.sampled package, when I encountered a strange residual beeping sound right after the clip ends. I am playing back four different audio files and the other three are working fine. I can not find a reason, why it is making this sound. Just to clarify, I checked the audio file in a editor and the beeping noise is not showing up and therefore has to be caused by Java. The following code is used to play the sounds (I am having trouble with case 1):
import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class SoundHandler implements SoundConstants{
URL url;
public SoundHandler() {
url = this.getClass().getResource("/sounds3.wav");
}
public void playSound(int sound) {
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(url));
clip.setFramePosition(0);
clip.start();
} catch (IOException | LineUnavailableException | UnsupportedAudioFileException e) {
e.printStackTrace();
}
}
}

Text to Speech Converter not working

I am trying to do text to speech converter using java code.And i am using freetts.jar to do this.I need to use this in my web application.
import com.sun.speech.freetts.*;
public class convert {
private static final String VOICENAME="kevin";
public static void call(){
Voice voice;
VoiceManager vm=VoiceManager.getInstance();
System.out.println("come");
voice=vm.getVoice(VOICENAME);
voice.allocate();
try{
voice.speak("wellcome to my world");
System.out.println("coming here good");
}
catch(Exception e){
System.out.println(e);
}
}
public static void main(String agrs[]){
call();
}
}
In the above code was not working voice.speak() method was not working .I don't know why.can any one help me to fix this?
And also i need to know how to make the text to voice conversion with own voice .
Thank you
There is no problem with the code. you must have added only freetts.jar to your buildpath. It will give nullpointer exception.
Add all the jars from the lib folder of freetts-1.2.2-bin to your buildpath.
The same code worked for me.
try and tell me.
And for your implementing your own voice: check out these articles
http://www.codeproject.com/Articles/182881/Text-to-Speech?msg=5074134#xx5074134xx
http://www.acapela-group.com/voices/voice-replacement/faq-my-own-voice/
I know i am posting it little late, but this may help someone. I tried the similar, and it worked for me. Please find the code below.
package com.mani.texttospeech;
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;
/**
*
* #author Manindar
*/
public class SpeechUtils {
SynthesizerModeDesc desc;
Synthesizer synthesizer;
Voice voice;
public void init(String voiceName) throws EngineException, AudioException, EngineStateError, PropertyVetoException {
if (desc == null) {
System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory");
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();
for (Voice voice1 : voices) {
if (voice1.getName().equals(voiceName)) {
voice = voice1;
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 {
SpeechUtils su = new SpeechUtils();
su.init("kevin16");
// su.init("kevin");
// su.init("mbrola_us1");
// su.init("mbrola_us2");
// su.init("mbrola_us3");
// high quality
su.doSpeak("Hi this is Manindar. Welcome to audio world.");
su.terminate();
}
}
And add the below dependencies to your pom.xml file.
<dependencies>
<dependency>
<groupId>net.sf.sociaal</groupId>
<artifactId>freetts</artifactId>
<version>1.2.2</version>
</dependency>
</dependencies>
Hope this will be helpful.

IOException markreset not supported with Java Sound on export

Ok so i made a game in java and i exported it. In Eclipse everything works perfectly but when i export the jar there are some problems. When you collide with another rectangle it should play a sound (In eclipse it works but not exported).
Here is my class for sounds:
package sound;
import java.io.InputStream;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class GameSounds
{
static String hitPath = "/resources/8bit_bomb_explosion.wav";
public static synchronized void hit()
{
try
{
InputStream audioInStream = GameSounds.class.getResourceAsStream(hitPath);
AudioInputStream inputStream = AudioSystem.getAudioInputStream(audioInStream);
Clip clip = AudioSystem.getClip();
clip.open(inputStream);
clip.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
and i used java -jar ProjectZero.jar to open up the console while playing and here is the error i get when it should play a sound:
java.io.IOException markreset not supported
at java.util.zip.InflaterInputStream.reset(Unknown Source)
at java.io.FilterInputStream.reset(Unknown Source)
at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(Unkno
wn Source)
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at sound.GameSounds.hit(GameSounds.java14)
at main.Main.doLogic(Main.java136)
at main.Main.run(Main.java100)
at java.lang.Thread.run(Unknown Source)
I tried exporting the resources into the jar but no success.
I tried putting the resources folder in the same folder with the jar but it doesn't work either.
Java Sound requires a repositionable input stream. Either use getResource(String) for an URL (out of which JS will create such a stream), or wrap the original stream to make it so.
E.G. copied from the Java Sound info. page.
import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;
public class LoopSound {
public static void main(String[] args) throws Exception {
URL url = new URL(
"http://pscode.org/media/leftright.wav");
Clip clip = AudioSystem.getClip();
// getAudioInputStream() also accepts a File or InputStream
AudioInputStream ais = AudioSystem.
getAudioInputStream( url );
clip.open(ais);
clip.loop(Clip.LOOP_CONTINUOUSLY);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// A GUI element to prevent the Clip's daemon Thread
// from terminating at the end of the main()
JOptionPane.showMessageDialog(null, "Close to exit!");
}
});
}
}
See also the embedded-resource info. page.

How to play an mp3 file in java

I am trying to play a song (mp3 file) in java. I have been looking around for a few hours now and none of the ways I found worked properly.
public void play()
{
String song = "song.mp3";
Media track = new Media(song);
MediaPlayer mediaPlayer = new MediaPlayer(track);
mediaPlayer.play();
}
I have tried doing that but it gives me errors.
I have imported JMF and JLayer.
I have also read other questions that are like this one on this forum and none of them have helped me.
I just need a hand to help play an mp3 file.
The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29
Here is the code for the class
public class SimplePlayer {
public SimplePlayer(){
try{
FileInputStream fis = new FileInputStream("File location.");
Player playMP3 = new Player(fis);
playMP3.play();
}catch(Exception e){System.out.println(e);}
}
}
and here are the imports
import javazoom.jl.player.*;
import java.io.FileInputStream;
For this you'll need to install Java Media Framework (JMF) in your PC. One you have it installed,then try this piece of code:
import javax.media.*;
import java.net.*;
import java.io.*;
import java.util.*;
class AudioPlay
{
public static void main(String args[]) throws Exception
{
// Take the path of the audio file from command line
File f=new File("song.mp3");
// Create a Player object that realizes the audio
final Player p=Manager.createRealizedPlayer(f.toURI().toURL());
// Start the music
p.start();
// Create a Scanner object for taking input from cmd
Scanner s=new Scanner(System.in);
// Read a line and store it in st
String st=s.nextLine();
// If user types 's', stop the audio
if(st.equals("s"))
{
p.stop();
}
}
}
You may run into unable to handle formaterror, that is because Java took out the MP3 support by default (pirate copyright issue), you are required to install a “JMF MP3 plugin” in order to play MP3 file.
Go Java’s JMF website to download it
http://java.sun.com/javase/technologies/desktop/media/jmf/mp3/download.html
To be sure that you are using a supported format file, check here:
http://www.oracle.com/technetwork/java/javase/formats-138492.html
If you are using windows7, you may have to read this as well:
https://forums.oracle.com/forums/thread.jspa?threadID=2132405&tstart=45
How about JavaFX application-
import java.net.URL;
import javafx.application.Application;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
public class VLC extends Application {
void playMedia() {
String mp3 = "00- Tu Hi Mera.mp3";
URL resource = getClass().getResource(mp3);
System.out.println(resource.toString());
Media media = new Media(resource.toString());
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
}
public static void main(String args[]) {
new VLC().playMedia();
}
#Override
public void start(Stage stage) throws Exception {
}
}

Java Media Framework - MP3 Issues

Im using Windows 7 and can "Java Platform SE Binary" in my sound mixer but yet still no sound seems to play.
My code is:
import javax.media.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLExc;
public class SimpleAudioPlayer {
private Player audioPlayer = null;
public SimpleAudioPlayer(URL url) throws IOException, NoPlayerException,
CannotRealizeException {
audioPlayer = Manager.createRealizedPlayer(url);
}
public SimpleAudioPlayer(File file) throws IOException, NoPlayerException,
CannotRealizeException {
this(file.toURL());
}
public void play() {
audioPlayer.start();
}
public void stop() {
audioPlayer.stop();
audioPlayer.close();
}
public static void main(String[] args) {
try{
File audioFile = new File("/t.mp3");
SimpleAudioPlayer player = new SimpleAudioPlayer(audioFile);
System.out.println();
System.out.println("-> Playing file '" +
audioFile.getAbsolutePath() + "'");
System.out.println(" Press the Enter key to exit");
player.play();
// wait for the user to press Enter to proceed.
System.in.read();
System.out.println("-> Exiting");
player.stop();
}catch(Exception ex){
ex.printStackTrace();
}
System.exit(0);
}
}
I use the Windows Preformance JMF edition. The MP3 im trying to play works fine in VLC/WMP so it cant be the file.
The code also throws no exceptions or error when running, it just doesnt seem to play the sound.
Is there something im missing? Like pulling the sound card? E.g. taking over it so i can play sound out of it?
Im overall aim is to to a MP3 streaming service using RTP/RTSP so any links,advice or tuturiols would be help as im currelnt using IBM JMF Tuturiol and Java Demo
Please ask if any more information is needed!
UPDATE-
Downloaded WAV FILE and it seemed to play, how can i make MP3s play?
Added formats and tried this code and still the same issue:
import java.io.File;
import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.PlugInManager;
import javax.media.format.AudioFormat;
public class SimpleAudioPlayer {
public static void main(String[] args) {
Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3);
Format input2 = new AudioFormat(AudioFormat.MPEG);
Format output = new AudioFormat(AudioFormat.LINEAR);
PlugInManager.addPlugIn(
"com.sun.media.codec.audio.mp3.JavaDecoder",
new Format[]{input1, input2},
new Format[]{output},
PlugInManager.CODEC
);
try {
Player player = Manager.createPlayer(new MediaLocator(new File("/t.mp3").toURI().toURL()));
player.start();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
Unable to handle format: mpeglayer3, 44100.0 Hz, 16-bit, Stereo, LittleEndian, Signed, 16000.0 frame rate, FrameSize=32768 bits
Failed to realize: com.sun.media.PlaybackEngine#62deaa2e
Error: Unable to realize com.sun.media.PlaybackEngine#62deaa2e
Thats the error!
As I thought, it's a missing codec.
I think this is what you need: http://www.oracle.com/technetwork/java/javase/download-137625.html

Categories