Sounds won't play in java.. JFrame and Canvas not Applet - java

I'm currently working on my first game in java and i'm trying to implement sounds when the spaceship is getting hit.. this is my code . I get a null pointer exception but my sound is in the right place "workspace/project/src/sounds/"
public class GameSounds
{
public static synchronized void hit()
{
try
{
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(GameSounds.class.getResourceAsStream("sounds/8bit_bomb_explosion.wav"));
clip.open(inputStream);
clip.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
here is the stacktrace
java.lang.NullPointerException
at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(Unknown Source)
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at sound.GameSounds.hit(GameSounds.java:16)
at main.Main.doLogic(Main.java:135)
at main.Main.run(Main.java:101)
at java.lang.Thread.run(Unknown Source)
package sound;
import java.io.InputStream;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class GameSounds
{
public static synchronized void hit()
{
try
{
String resPath = "/sounds/8bit_bomb_explosion.wav"; // *** this is the key ***
InputStream audioInStream = GameSounds.class.getResourceAsStream(resPath);
System.out.println("is audioInStream null?: " + (audioInStream == null)); // test it!
AudioInputStream inputStream = AudioSystem.getAudioInputStream(audioInStream); Clip clip = AudioSystem.getClip();
clip.open(inputStream);
clip.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
thanks for advices now it works

In all likelihood, you are not getting the resource with the correct path. Understand that resource paths are based on where the class loader looks to load class files and not on where the src or "user.dir" directory is.
Perhaps you want to do:
// almost always better to break up a long code line into smaller lines.
String resPath = "/sounds/8bit_bomb_explosion.wav"; // *** this is the key ***
InputStream audioInStream = GameSounds.class.getResourceAsStream(resPath);
System.out.println("is audioInStream null?: " + (audioInStream == null)); // test it!
AudioInputStream inputStream = AudioSystem.getAudioInputStream(audioInStream);
Again the path String will depend on where your class files are located in relation to your src directory.

I have had the same problems. But after searching for hours I found Javazoom which is a external libery you can import into your project and makes it much more easy to play sounds:
http://www.javazoom.net/index.shtml
You can use it like this:
import javazoom.jl.player.advanced.*;
class SoundJLayer extends PlaybackListener implements Runnable
{
private String filePath;
private AdvancedPlayer player;
private Thread playerThread;
public SoundJLayer(String filePath)
{
this.filePath = filePath;
}
public void play()
{
try
{
String urlAsString =
"file:///"
+ new java.io.File(".").getCanonicalPath()
+ "/"
+ this.filePath;
this.player = new AdvancedPlayer
(
new java.net.URL(urlAsString).openStream(),
javazoom.jl.player.FactoryRegistry.systemRegistry().createAudioDevice()
);
this.player.setPlayBackListener(this);
this.playerThread = new Thread(this, "AudioPlayerThread");
this.playerThread.start();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public void stop() {
player.stop();
}
// PlaybackListener members
public void playbackStarted(PlaybackEvent playbackEvent)
{
}
public void playbackFinished(PlaybackEvent playbackEvent)
{
}
// Runnable members
public void run()
{
try
{
this.player.play();
}
catch (javazoom.jl.decoder.JavaLayerException ex)
{
ex.printStackTrace();
}
}
}
After that you just have to create a new SoundJLayer-Object and start ir with play()
Hope this is helpful,
Jan

Related

How to play a wav file using Java?

I would like to play a wav file and after I googled it I found this script but it doesn't work.
(It didn't throw any exceptions nor have compiling problems)
import java.io.File;
import films.Film;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class MusicStorage {
/**
* Opens a wav file and plays it
* #param args
*/
public void play(Film song) {
try {
Clip sound = AudioSystem.getClip();
sound.open(AudioSystem.getAudioInputStream(new File(song.getClip())));
sound.start();
while (sound.isRunning())
Thread.sleep(1000);
sound.close();
} catch (Exception e) {
System.out.println("Whatever" + e);
}
}
}
import audio.MusicStorage;
import films.Film;
public class Aplication {
private static Film gladiator = new Film("Gladiator", "gladiator.wav");
private static MusicStorage storage = new MusicStorage();
public static void main(String[] args) {
storage.play(gladiator);
}
}
public class Film {
private String name;
private String clip;
public Film(String name, String clip) {
this.name = name;
this.clip = clip;
}
public String getClip() {
return clip;
}
public String getName() {
return name;
}
}
I have added all the code that I have so I hope it would be clear to solve my problem
Just remove the while loop from your code and it should be fixed. The while loop is making the thread sleep so it can't play the audio file.
public void play(Film song) {
try {
Clip sound = AudioSystem.getClip();
sound.open(AudioSystem.getAudioInputStream(new File(song.getClip())));
sound.start();
} catch (Exception e) {
System.out.println("Whatever" + e);
}
}
}

Access restriction: The type Player is not accessible due to restriction on required library C:\Program Files (x86)\Java\jre7\lib\ext\jmf.jar

I'm trying LiveAudioStreaming in java. For livestreming through JMF. I'm getting following error.
Access restriction: The type Player is not accessible due to restriction on required library C:\Program Files (x86)\Java\jre7\lib\ext\jmf.jar.
Please help. I used code from this link
Here is the code:
package com.simpleaudioplayer.simpleaudioplayer;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.media.*; // import JMF classes
import javax.swing.JFileChooser;
public class Main {
private Player audioPlayer = null;
public SimpleAudioPlayer(URL url) {
try {
//MediaLocator ml=new MediaLocator(url);
audioPlayer = Manager.createPlayer(url);
} catch (Exception ex) {
System.out.println(ex);
}
}
public SimpleAudioPlayer(File file) throws MalformedURLException {
this(file.toURI().toURL());
}
public void play() {
audioPlayer.start(); // start playing
}
public void stop() {
audioPlayer.stop(); //stop playing
audioPlayer.close();
}
public static void main(String[] args) {
try {
// TODO code application logic here
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(null);
File file = fc.getSelectedFile();
SimpleAduioPlayer sap = new SimpleAduioPlayer(file);
sap.play();
//sap.stop();
} catch (MalformedURLException ex) {
System.out.println(ex);
}
}
}

Better way of resetting java AudioStream

As of now, i am using AudioPlayer to create sound effects for my game, and I am struggling to find an easy way to reset the audio before I begin playing it again. As of now I am just reloading the AudioStream entirely, heres my code, any suggestions are welcome.
package resources;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import javax.sound.sampled.Clip;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
public class Audio {
private static HashMap<String, AudioStream> sounds = new HashMap<String, AudioStream>();
private static HashMap<String, Long> times = new HashMap<String, Long>();
Clip c;
public static AudioStream getAudio(String s){
if(sounds.containsKey(s))
return sounds.get(s);
return null;
}
public static void loadAllAudio(){
File f = new File("res/sounds");
String[] files = f.list();
for(String s:files){
if(s.endsWith(".wav")){
loadAudio(s);
System.out.println("Loaded Audio: "+s);
}
}
}
public static double getSoundLength(String sound){
return getAudio(sound).getLength()/192000.0;
}
public static void playSound(String name){
resetSound(name);
times.put(name, System.nanoTime());
AudioPlayer.player.start(sounds.get(name));
}
public static void resetSound(String name){
loadAudio(name);
}
public static void stopSound(String sound){
AudioPlayer.player.stop(sounds.get(sound));
times.put(sound, System.nanoTime());
}
private static void loadAudio(String name){
try {
File f = new File("res/sounds/"+name);
sounds.put(name, new AudioStream(new FileInputStream(f)));
times.put(name, 0L);
} catch (Exception e) {}
}
public static double getTime(String sound) {
long time = times.get(sound);
if(time==0)
return 0;
return (System.nanoTime()-time)/1E9;
}
}
The line I would like to replace is:
public static void playSound(String name){
---------resetSound(name);--------- THIS LINE
times.put(name, System.nanoTime());
AudioPlayer.player.start(sounds.get(name));
}
You can use JLayer which supports .mp3
An example how to play sound with JLayer:
new Thread(()->{
try {
FileInputStream file = new FileInputStream("path ..../audio.mp3"); //initialize the FileInputStream
Player player= new Player(file); //initialize the player
player.play(); //start the player
} catch (Exception e) {
e.printStackTrace();
}
}).start();
Note:
Note that i am using a separate Thread cause if not the App will stack.

getResource() inside of .wav sound player class

Simple GUI application for playing sound clips after user selects one with a radio button and pushes the play button. After clean and build, execution from the JAR file results in no sound being played when a clip is selected and the play button is pushed.
Conditions: NetBeans IDE, sounds play successfully in the IDE pathed to the package, path to .wav files in JAR is correct, files are in the executable JAR in the correct directory, uses 2 classes: one for the GUI and a .wav handler class (both work successfully in the IDE. More details in screen shots. I am thinking that there should be a getResource() method call in the Player calss but I don't know how to write it.
The code snippet used to call the resource from within the GUI class. The base is new Player("whateverthefilepathis").start(). (this works fine in the IDE, so no issue there):
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
if (jRadioButton1.isSelected()){
URL file = QuotesButtonUI.class.getResource("/my/sounds/fear_converted.wav");
new Player (file.getFile()).start();
}
else if (jRadioButton2.isSelected()){
URL file = QuotesButtonUI.class.getResource("/my/sounds/initiated_converted.wav");
new Player (file.getFile()).start();
}
This is the Player class used to process the .wav. Within the GUI class, I am using the new Player().start() call. I am thinking that there should be a getResource() call in the Player class but I don't know for sure.
package my.quotesbutton;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
public class Player extends Thread {
private String filename;
private Position curPosition;
private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb
enum Position {
LEFT, RIGHT, NORMAL
};
public Player(String wavfile) {
filename = wavfile;
curPosition = Position.NORMAL;
}
public Player(String wavfile, Position p) {
filename = wavfile;
curPosition = p;
}
public void run() {
File soundFile = new File(filename);
if (!soundFile.exists()) {
System.err.println("Wave file not found: " + filename);
return;
}
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
} catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
return;
} catch (IOException e1) {
e1.printStackTrace();
return;
}
AudioFormat format = audioInputStream.getFormat();
SourceDataLine auline = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
try {
auline = (SourceDataLine) AudioSystem.getLine(info);
auline.open(format);
} catch (LineUnavailableException e) {
e.printStackTrace();
return;
} catch (Exception e) {
e.printStackTrace();
return;
}
if (auline.isControlSupported(FloatControl.Type.PAN)) {
FloatControl pan = (FloatControl) auline
.getControl(FloatControl.Type.PAN);
if (curPosition == Position.RIGHT)
pan.setValue(1.0f);
else if (curPosition == Position.LEFT)
pan.setValue(-1.0f);
}
auline.start();
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
try {
while (nBytesRead != -1) {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
if (nBytesRead >= 0)
auline.write(abData, 0, nBytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return;
} finally {
auline.drain();
auline.close();
}
}
}
You can't access anything inside a jar file using the java.io.File API, simply because items inside a jar are not files.
You need indeed, as you suspected, to use a getResource() method (or getResourceAsStream()): http://docs.oracle.com/javase/tutorial/deployment/webstart/retrievingResources.html
That may look counterintuitive at first, but getResource() works with files as well as jars (or even remote located resources in case of a webapp, as in the linked tutorial), the ClassLoader will deal with the dirty details how the resource is physically accessed. In short: never use the File API for resources - resources should only be accessed using the resource API.

Android External File Inconsistently Appearing

I'm using an IntentService to append single NMEA strings to a log file stored in the external public storage on an Android device, but I'm getting inconsistent behavior.
First off the log file does not appear when the device is connected for USB debugging. I read that many Android devices cannot write to external storage when connected via USB, but even when it is run disconnected from USB, it may take several times of turning it on and off and rerunning the applications before the log file appears in the file system. If I do not clear the log, I still have to restart the phone before it will begin appending to the file again.
How can I get the file to appear consistently everytime?
import android.app.IntentService;
import android.content.Intent;
public class LogFileService extends IntentService {
DebugLog debug = new DebugLog("LogFileService");
public static final String GPS_STR = "GPS_STR";
public static final String FILE_PATH = "FILE_PATH";
public static final String FILE_NAME = "gps_data.txt";
public LogFileService() {
super("LogFileService");
}
#Override
protected void onHandleIntent(Intent intent) {
debug.log("Handling intent");
String data = intent.getStringExtra(GPS_STR);
debug.log("Writing " + data);
GpsLogFile logFile = new GpsLogFile(FILE_NAME);
logFile.open();
logFile.write(data);
logFile.close();
}
#Override
public void onCreate() {
super.onCreate();
debug.log("Created");
}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import android.content.Context;
import android.os.Environment;
public class GpsLogFile {
DebugLog debug = new DebugLog("LogFile");
private File filePath = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS
);
private File logFile = null;
private String fileName = null;
private PrintWriter fileOut = null;
public GpsLogFile(String name) {
fileName = name;
}
public void open() {
try {
filePath.mkdirs();
if (!isExternalMediaAvailable()) {
throw new IOException("External media not available.");
}
logFile = new File(filePath, fileName);
//logFile.mkdirs();
if (!logFile.exists()) {
logFile.createNewFile();
}
fileOut = new PrintWriter(
new FileOutputStream(logFile.getAbsolutePath(), true)
);
} catch (IOException e) {
debug.log("Unable to open file.");
debug.log(e.getMessage());
}
}
public void write(String data) {
debug.log("Writing to " + logFile.getAbsolutePath() + " " + data);
try {
fileOut.write(data);
//fileOut.newLine();
checkPrintWriterError(fileOut);
fileOut.flush();
} catch (IOException e) {
debug.log("Unable to write");
debug.log(e.getMessage());
}
}
public void close() {
if (null != fileOut) {
try {
fileOut.close();
checkPrintWriterError(fileOut);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void checkPrintWriterError(PrintWriter writer) throws IOException {
if (true == writer.checkError()) {
throw new IOException("Print writer error.");
}
}
}

Categories

Resources