Chu
Chu

Reputation: 478

Playing sound in Java 7

I am trying to play a sound file in Java. I have written this code:

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class SoundBang
{
    private File _file;
    private AudioInputStream _audio;
    private Clip _clip;

    public SoundBang( )
    {
        _file = new File( "file/sound/bang.wav" );

        try
        {
            _audio = AudioSystem.getAudioInputStream( _file );
            _clip = AudioSystem.getClip( );
            _clip.open( _audio );
            _clip.start( );
        }
        catch ( LineUnavailableException e )
        {
            e.printStackTrace( );
        }
        catch ( IOException e )
        {
            e.printStackTrace( );
        }
        catch ( UnsupportedAudioFileException e )
        {
            e.printStackTrace( );
        }
    }

    public static void main ( String[ ] args )
    {
        new SoundBang( );
    }
}

The problem is I do not hear anything when I run this code.

The URL of the sound file is correct (I tested it by printing the Absolute URL and it is fine). I'm using Eclipse Juno, openjdk-7 and Fedora 17 with KDE.

Upvotes: 2

Views: 785

Answers (1)

hsanders
hsanders

Reputation: 1898

Couple things:

  1. clip.start spawns a new thread to execute in the background and it dies when the app dies. Try sleeping after starting the clip.
  2. Is it necessary to seek forward after you start? It seems like that's just an extra line.

Try making your main method:

public static void main ( String[ ] args )
{
    new SoundBang( );
    Thread.sleep(2000); // Sleep 2 seconds
}

Upvotes: 2

Related Questions