1

Hello I'm trying to play a sound in java the code looks like this:

public void playSound(String sound) {
    try {
        InputStream in = new FileInputStream(new File(sound));
        AudioStream audio = new AudioStream(in);
        AudioPlayer.player.start(audio);
    } catch (Exception e) {}
}

I imported sun.audio*; however get an error:

Access restriction: The type 'AudioPlayer' is not API (restriction on required library 'C:\Program Files\Java\jre7\lib\rt.jar')

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Day
  • 35
  • 1
  • 1
  • 6

1 Answers1

8

The following program plays a 16-bit wav sound from eclipse if we use javax.sound.

import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
import javax.swing.*;

// To play sound using Clip, the process need to be alive.
// Hence, we use a Swing application.
public class SoundClipTest extends JFrame {

   // Constructor
   public SoundClipTest() {
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      this.setTitle("Test Sound Clip");
      this.setSize(300, 200);
      this.setVisible(true);       
      // You could also get the sound file with a URL
      File soundFile = new File("C:/Users/niklas/workspace/assets/Sound/sound.wav");
      try ( // Open an audio input stream.            
            AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);            
            // Get a sound clip resource.
            Clip clip = AudioSystem.getClip()) {
         // Open audio clip and load samples from the audio input stream.
         clip.open(audioIn);
         clip.start();
      } catch (UnsupportedAudioFileException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } catch (LineUnavailableException e) {
         e.printStackTrace();
      }
   }

   public static void main(String[] args) {
      new SoundClipTest();
   }
}
Luke Hutchison
  • 8,186
  • 2
  • 45
  • 40
Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424
  • 2
    Nit pick: You really don't need the frame, it's just clutter, but having said that, there's no reason to extend from `JFrame` as you're adding no new functionality to the class and you should be be ensuring that the UI is constructed within the context of the Event Dispatching Thread. See [Initial Threads](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html) for more details – MadProgrammer Aug 07 '14 at 00:34
  • Thank you so much! This works really great, and because of the way it works I can have multiple sounds over lapping each other (like music and sound effects) – Day Aug 07 '14 at 14:14
  • 1
    2016 and this code still works in java 8 (only one that worked for me, btw). PS: ONLY works with .wav extension (do not try to use mp3). – TroniPM Dec 05 '16 at 12:52
  • This works perfectly. Is there a way to control the volume? – Dhruv Erry Jun 13 '20 at 06:54