I have the problem that after i export my java project no sound is playing.
I searched in the internet and i found that:
Main.class.getResourceAsStream("fileloc");solves that problem
But my class uses this..
Where is the problem?
public class Sounds {
private static Clip eat;
public static Clip collect;
private static Clip lsd;
private static AudioInputStream inputStream;
private static FloatControl gainControl;
public static void getSounds(){
try{
eat = getClip("/sound/collect/eat.wav");
collect = getClip("/sound/collect/collect.wav");
lsd = getClip("/sound/LSD.wav");
} catch(LineUnavailableException | UnsupportedAudioFileException| IOException e){
e.printStackTrace();
}
}
private static Clip getClip(String loc) throws LineUnavailableException, UnsupportedAudioFileException, IOException{
Clip c = AudioSystem.getClip();
inputStream = AudioSystem.getAudioInputStream(Spielfeld.class.getResourceAsStream(loc));
c.open(inputStream);
gainControl = (FloatControl) c.getControl(FloatControl.Type.MASTER_GAIN);
gainControl.setValue(+6.0f);
c.setMicrosecondPosition(0);
return c;
}
public static void playSound(final String url) {
switch(url){
case "collect/collect.wav": collect.start(); collect.setMicrosecondPosition(0); break;
case "collect/eat.wav": eat.start(); eat.setMicrosecondPosition(0); break;
case "LSD.wav": lsd.start(); lsd.setMicrosecondPosition(0); break;
}
}
}
Thank you for your help
No sound after export to jar
Thank you trinityalps ;) (https://stackoverflow.com/users/5012832/trinityalps)
Related
I'm creating a video record file (avi) with javacv after creation converting this file to an mp4 file with Jaffree. When i try to delete the now redundant avi file it throws the FileSystemException.
I've already released all the file holding Objects but still the exception is being thrown. Also tried to force the deletion with apache common io FileUtils.forceDelete(sample.getFile()); still having the same Exception.
public class PacketRecorderTest {
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd__hhmmSSS");
private static final int RECORD_LENGTH = 10000;
private static final boolean AUDIO_ENABLED = false;
static String inputFile = "rtsp://184.72.239.149/vod/mp4:BigBuckBunny_115k.mov";
static String outputFile = "C:\\Users\\team3\\Desktop\\User\\Vinay\\javacppffmpeg\\frame.avi";
public static void main(String[] args) throws FrameRecorder.Exception, FrameGrabber.Exception, InterruptedException{
packetRecord(inputFile,outputFile);
jafreeToMp4(outputFile, "C:\\Users\\team3\\Desktop\\User\\Vinay\\javacppffmpeg\\frame.mp4");
try {
Files.delete(Paths.get(outputFile));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void packetRecord(String inputFile, String outputFile) throws FrameGrabber.Exception, FrameRecorder.Exception {
FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
grabber.start();
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(
outputFile,
1280,
720);
recorder.start(grabber.getFormatContext());
recorder.setFormat("avi");
recorder.setPixelFormat(AV_PIX_FMT_YUV420P);
recorder.setVideoOption("crf", "22");
recorder.setVideoQuality(0);
recorder.setFrameRate(15);
recorder.start();
avcodec.AVPacket packet;
long t1 = System.currentTimeMillis();
while ((packet = grabber.grabPacket()) != null) {
recorder.recordPacket(packet);
if ((System.currentTimeMillis() - t1) > RECORD_LENGTH) {
break;
}
}
grabber.stop();
recorder.stop();
recorder.release();
grabber.release();
}
public static void jafreeToMp4 (String inputFile, String outputFile) {
Path BIN = Paths.get("C:\\ffmpeg\\shared\\bin");
Path VIDEO_MP4 = Paths.get(inputFile);
Path OUTPUT_MP4 = Paths.get(outputFile);
FFmpegResult result = FFmpeg.atPath(BIN)
.addInput(UrlInput.fromPath(VIDEO_MP4))
.addOutput(UrlOutput.toPath(OUTPUT_MP4)
)
.execute();
}
}
java.nio.file.FileSystemException: C:\Users\team3\Desktop\User\Vinay\javacppffmpeg\frame.avi: The process cannot access the file because it is being used by another process.
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:86)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
at sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:269)
at sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:103)
at java.nio.file.Files.delete(Files.java:1126)
at playground.PacketRecorderTest.main(PacketRecorderTest.java:39)
I can't tell for sure, as I don't have immediate access to the libraries you're using. However, it looks to me as though you still have open InputStreams and OutputStreams. My suggestions would look something like this, depending on the return type of the helper methods:
try(InputStream in = UrlInput.fromPath(VIDEO_MP4);
OutputStream out = UrlOutput.toPath(OUTPUT_MP4)) {
FFmpegResult result = FFmpeg.atPath(BIN)
.addInput(in)
.addOutput(out)
.execute();
}
This will close the resources after the statement is complete.
Was calling the start() method twice recorder.start(grabber.getFormatContext()); and start(). So may the first call may have left the references untracked.
I have some questions about playing sound in Java and I hope you can help me out.
1. How can I stop a playing sound with a "Stop" button?
2. How can I slow down (or cooldown time) a sound?
3. I want to create a option frame where I can adjust volume and have mute option, how can I do that?
This is my code:
private void BGM() {
try {
File file = new File(AppPath + "\\src\\BGM.wav");
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(file));
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
Any help will be greatly appreciated, and, Have a nice day!
You're working in an Object Oriented programming lanuage, so let's take advantage of that and encapsulate the management of the clip/audio into a simple class...
public class AudioPlayer {
private Clip clip;
public AudioPlayer(URL url) throws IOException, LineUnavailableException, UnsupportedAudioFileException {
clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(url.openStream()));
}
public boolean isPlaying() {
return clip != null && clip.isRunning();
}
public void play() {
if (clip != null && !clip.isRunning()) {
clip.start();
}
}
public void stop() {
if (clip != null && clip.isRunning()) {
clip.stop();
}
}
public void dispose() {
try {
clip.close();
} finally {
clip = null;
}
}
}
Now, to use it, you need to create a class instance field which will allow you to access the value from anywhere within the class you want to use it...
private AudioPlayer bgmPlayer;
Then, when you need it, you create an instance of AudioPlayer and assign it to this variable
try {
bgmPlayer = new AudioPlayer(getClass().getResource("/BGM.wav"));
} catch (IOException | LineUnavailableException | UnsupportedAudioFileException ex) {
ex.printStackTrace();
}
Now, when you need to, you simply call bgmPlayer.play() or bgmPlayer.stop()
I'm trying to build a game that uses sound effects. I haven't dealt with the Java API before so I may be making some mistakes. That said though, the effects work great — my only problem is that I get a strange buzzing sound for maybe a second whenever my program exits.
Any idea how I might get rid of it? Right now I'm trying to kill any playing sounds just before the exit takes place with the killLoop() method, but that isn't getting me anywhere.
I'd appreciate your help!
public class Sound
{
private AudioInputStream audio;
private Clip clip;
public Sound(String location)
{
try {
audio = AudioSystem.getAudioInputStream(new File(location));
clip = AudioSystem.getClip();
clip.open(audio);
}
catch(UnsupportedAudioFileException uae) {
System.out.println(uae);
}
catch(IOException ioe) {
System.out.println(ioe);
}
catch(LineUnavailableException lua) {
System.out.println(lua);
}
}
public void play()
{
clip.setFramePosition(0);
clip.start();
}
public void loop()
{
clip.loop(clip.LOOP_CONTINUOUSLY);
}
public void killLoop()
{
clip.stop();
clip.close();
}
}
public class Athenaeum
{
public static void main(String[] args) throws IOException
{
final Game game = new Game();
GUI athenaeumGui = new GUI(game);
athenaeumGui.setSize(GUI.FRAME_WIDTH, GUI.FRAME_HEIGHT);
athenaeumGui.setTitle("Athenaeum");
athenaeumGui.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
athenaeumGui.setLocationRelativeTo(null);
athenaeumGui.setMinimumSize(new Dimension(GUI.FRAME_WIDTH, GUI.FRAME_HEIGHT));
athenaeumGui.buildGui();
athenaeumGui.setVisible(true);
athenaeumGui.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we)
{
game.killAudio(); // method calls Sound.killLoop()
System.exit(0);
}
});
}
}
In Java api, they say that the AudioInputStream class has a ".close()" method that "Closes this audio input stream and releases any system resources associated with the stream". Maybe this is something you can try.
Well, the title says all, I tried playing a wav file using javax.sound and nothing is happening. I have tried many different files without any luck.
public static void main(String[] args) throws IOException, UnsupportedAudioFileException, LineUnavailableException
{
File in = new File("C:\\Users\\Sandra\\Desktop\\music\\rags.wav");
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(in);
Clip play = AudioSystem.getClip();
play.open(audioInputStream);
FloatControl volume= (FloatControl) play.getControl(FloatControl.Type.MASTER_GAIN);
volume.setValue(1.0f); // Reduce volume by 10 decibels.
play.start();
}
As, has already begin stated, you need to prevent the main thread from exiting, as this will cause the JVM to terminate.
Clip#start is not a blocking call, meaning that it will return (soon) after it is called.
I have no doubt that there are many ways to approach this problem and this is just a simple example of one of them.
public class PlayMusic {
public static void main(String[] args) throws InterruptedException {
Clip play = null;
try {
File in = new File("C:\\Users\\Public\\Music\\Sample Music\\Kalimba.wav");
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(in);
play = AudioSystem.getClip();
play.open(audioInputStream);
FloatControl volume = (FloatControl) play.getControl(FloatControl.Type.MASTER_GAIN);
volume.setValue(1.0f); // Reduce volume by 10 decibels.
play.start();
// Loop until the Clip is not longer running.
// We loop this way to allow the line to fill, otherwise isRunning will
// return false
//do {
// Thread.sleep(15);
//} while (play.isRunning());
play.drain();
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
ex.printStackTrace();
} finally {
try {
play.close();
} catch (Exception exp) {
}
}
System.out.println("...");
}
}
The actual solution will depend on your needs.
Java's sound Clip requires an active Thread to play the audio input file otherwise the application exits before the file can be played. You could add
JOptionPane.showMessageDialog(null, "Click OK to stop music");
after calling start.
The proper way to play the audio clip is to drain the line as explained in Playing Back Audio.
So your main should look like this:
public static void main(String[] args) throws IOException,
UnsupportedAudioFileException, LineUnavailableException
{
File in = new File("C:\\Users\\Sandra\\Desktop\\music\\rags.wav");
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(in);
Clip play = AudioSystem.getClip();
play.open(audioInputStream);
FloatControl volume= (FloatControl) play.getControl(FloatControl.Type.MASTER_GAIN);
volume.setValue(1.0f); // Reduce volume by 10 decibels.
play.start();
play.drain();
play.close();
}
play.drain() blocks until all the data is played.
Here playing a clip
public static void main(String[] args) throws Exception {
File in = new File("C:\\Users\\Sandra\\Desktop\\music\\rags.wav");
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(in);
Clip play = AudioSystem.getClip();
play.open(audioInputStream);
FloatControl volume= (FloatControl)play.getControl(FloatControl.Type.MASTER_GAIN);
volume.setValue(1.0f); // Reduce volume by 10 decibels.
play.start();
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!");
}
});
}
Your program is terminating before the sound has the time to be played. I would do play.start(); in some threading way (invokeLater, ...), and also find a way to wait until the sound has finished (Reimeus suggested one).
A lead :
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
...
play.start();
JOptionPane.showMessageDialog(null, "Click OK to stop music");
}
});
}
If you just want to play an audio, here's a way.
The audioFileDirectory String variable needs the correct path to your audio file, otherwise an exception will be thrown and the program won't run.
Example of having the right audio file directory in a project if using an IDE:
Make a folder inside src folder, e.g: "music" and put an audio file there
audioFileDirectory = "/music/name_of_audio_file";
The important part for an audio to play is that the main thread of the program needs somehow to be "alive", so the line
Thread.sleep(audio.getMicrosecondLength()/1000);
is where the main thread is "alive", and the argument audio.getMicrosecondLength()/1000 is the time that will be "alive", which is the whole length of the audio file.
public class AudioTest
{
void playAudio() throws Exception
{
String audioFileDirectory = "your_audioFileDirectory";
InputStream is = getClass().getResourceAsStream(audioFileDirectory);
BufferedInputStream bis = new BufferedInputStream(is);
AudioInputStream ais = AudioSystem.getAudioInputStream(bis);
Clip audio = AudioSystem.getClip();
audio.open(ais);
audio.loop(Clip.LOOP_CONTINUOUSLY);
audio.start();
Thread.sleep(audio.getMicrosecondLength()/1000);
audio.close();
} // end playAudio
public static void main(String[] args)
{
try
{
new AudioTest().playAudio();
}
catch (Exception e)
{
System.out.println("Class: " + e.getClass().getName());
System.out.println("\nMessage:\n" + e.getMessage() + "\n");
e.printStackTrace();
}
} // end main
} // end class AudioTest
Problem solved!!! I've transfered the whole folder from desktop under c:\ and for some reason it is working
I've a very weird scenario.
I try to run my partner's version which is fully working without any exceptions in his computer- it is the same project..
Any ideas?
Relevant code added..
public class DJ implements Runnable
{
private static final int k_SoundLoop = 500;
private static final int k_NumberOfSong = 2;
private static final int k_CairoTrainSong = 0;
private static final int k_MachineSong = 1;
private ArrayList<Clip> m_Records = new ArrayList<Clip>();
private int m_CurrentRecored = 0;
private Thread m_MusicThread = null;
private AppletContext m_AppletContext;
//java.net.URL m_CodeBase;
//AppletContext ac;
public DJ()
{
try
{
createClip(getClass().getResource("/Music/train.au"));
createClip(getClass().getResource("/Music/machine.au"));
}
catch (Exception ex)
{
Logger.getLogger(DJ.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void createClip(URL i_SoundFileURL) throws Exception
{
File soundFile = new File(i_SoundFileURL.getFile());
AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);
// load the sound into memory (a Clip)
DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(sound);
m_Records.add(clip);
}
public void play()
{
m_Records.get(m_CurrentRecored).loop(k_SoundLoop);
}
public void play(int i_RecoredNumber)
{
stopCurrentClipIfNeeded();
m_CurrentRecored = i_RecoredNumber;
m_Records.get(m_CurrentRecored).start();
}
public void stop()
{
stopCurrentClipIfNeeded();
m_CurrentRecored = 0;
}
public void stop(int i_RecordNumber)
{
m_Records.get(i_RecordNumber).stop();
}
public void Next()
{
stopCurrentClipIfNeeded();
m_CurrentRecored = ((m_CurrentRecored+1)%k_NumberOfSong);
m_Records.get(m_CurrentRecored).start();
}
private void stopCurrentClipIfNeeded()
{
if (m_Records.get(m_CurrentRecored).isRunning())
{
m_Records.get(m_CurrentRecored).stop();
}
}
public boolean IsRunning()
{
return m_Records.get(m_CurrentRecored).isRunning();
}
public void CloseRecoredSet()
{
for (Clip clip : m_Records)
{
clip.close();
}
}
#Override
public void run()
{
m_Records.get(m_CurrentRecored).start();
}
}
Thanks
I'm consistently getting this:
08/10/2011 23:47:48 LogicEngine.DJ <init>
SEVERE: null
java.io.FileNotFoundException: C:\Users\Dan\Desktop\CairoNightTrain\CairoNightTrain\CairoNightTrainClient\src\Music\train.au (System can not find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at com.sun.media.sound.WaveFileReader.getAudioInputStream(WaveFileReader.java:205)
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1162)
at LogicEngine.DJ.createClip(DJ.java:56)
at LogicEngine.DJ.<init>(DJ.java:42)
at GUI.JPanelGameApplet$1.run(JPanelGameApplet.java:63)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:199)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatc
C:\Users\Dan\Desktop\CairoNightTrain\CairoNightTrain\CairoNightTrainClient\src\Music\train.au
Is your friend called Dan by any chance? It can't find this file. I think it's pretty clear?
What does this print?
File file = new File("/Music/train.au");
String absolutePathOfFile = file.getAbsolutePath();
System.out.println(" The absolute path is " + absolutePathOfFile);