package net.NitroCruze.mrpg.baseengine.music;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
public class CPSound implements Runnable{
AudioInputStream as1;
AudioFormat af;
Clip clip1;
DataLine.Info info;
Line line1;
public CPSound() {
Thread soundThread;
soundThread = new Thread(this, "Sound");
soundThread.start();
}
public void play() {
try{
as1 = AudioSystem.getAudioInputStream(new FileInputStream(new File("/res/music.wav")));
af = as1.getFormat();
clip1 = AudioSystem.getClip();
info = new DataLine.Info(Clip.class, af);
line1 = AudioSystem.getLine(info);
}
catch(Exception e)
{
}
if ( ! line1.isOpen() )
{
try
{
clip1.open(as1);
}
catch (Exception e)
{
}
clip1.loop(Clip.LOOP_CONTINUOUSLY);
clip1.start();
}
}
public void run()
{
play();
}
}
Why does this not work? It gives me a NullPointerException?
I found out why it wasn't working! I had put "/" before 'res/music.wav' which caused the file loading system to think I was loading from a DRIVE (eg C:/ F:/), but there was nothing before that / so it thought it was loading from a null drive, which cannot exist.
Related
I am attempting to play audio for a program and I need the AudioStream class and the AudioPlayer class, but when I attempt to import them Eclipse gives me an error.
Method where used:
public static void playMusic(String filepath) {
InputStream music;
try {
music = new FileInputStream(new File(filepath));
AudioStream audio = new AudioStream(music);
AudioPlayer.player.start(audio);
} catch(Exception e) {
JOptionPane.showMessageDialog(null, "Error");
}
}
Imports:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.swing.JOptionPane;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
I've tried to search similiar question to this, but couldn't find. I don't know how i can stop my sound when button is released, and also, i don't know how to loop sound only one by one, when i hold button it plays again while previous loop is still playing, and the sound is becoming a loop from ∞ sounds.
Here's the code:
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Component;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class test {
String b[]={"Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M"};
Action[] actions = new AbstractAction[26];
public test() throws Exception {
JFrame frame = new JFrame();
JButton[] buttons = new JButton[26];
for(int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton(b[i]);
buttons[i].setSize(80, 80);
buttons[i].addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
System.out.println(e.getKeyChar());
playSound(new File("loopbase/loop1/"+e.getKeyChar()+".wav"));
}
public void keyReleased(KeyEvent e){
}
});
frame.add(buttons[i]);
}
JPanel contentPane = (JPanel)frame.getContentPane();
frame.setLayout(new GridLayout(3, 5, 5, 3));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
try {
new test();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void playSound(File soundName)
{
try
{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundName.getAbsoluteFile( ));
Clip clip = AudioSystem.getClip( );
clip.open(audioInputStream);
clip.start( );
}
catch(Exception ex)
{
System.out.println("Error with playing sound.");
ex.printStackTrace( );
}
}
}
Anyone can help me with this issue?
I don't know how i can stop my sound when button is released?
You can stop the the clip by using DataLine#stop(). Just keep the reference of last played clip and call below line to stop it.
clip.stop();
Note: You can store it somewhere in static variable.
Sample code:
private static Clip clip;
...
public void keyReleased(KeyEvent e) {
if (clip != null) {
clip.stop();
}
}
...
public void playSound(File soundName) {
...
clip = AudioSystem.getClip();
...
}
When I hold the Button it plays again while previous loop is still playing.
This is because for every keyPress you are creating a new File object. That should be avoided.
To stop sound:
I would add a boolean parameter to playsound method. And depending upon the parameter passed I would call clip.start() or clip.stop() (superclass DataLine has a stop method) .
Call playsound(filename,false); in keyReleased.
public void playSound(File soundName , boolean start)
{
try
{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundName.getAbsoluteFile( ));
Clip clip = AudioSystem.getClip( );
clip.open(audioInputStream);
if(start == true)
clip.start();
else
clip.stop();
}
catch(Exception ex)
{
System.out.println("Error with playing sound.");
ex.printStackTrace( );
}
}
I am attempting to add an audio player to my application. Here's the code from the class that handles audio playing:
package me.pogostick29.audiorpg.audio;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
public class AudioPlayer {
private AudioPlayer() { }
private static AudioPlayer instance = new AudioPlayer();
public static AudioPlayer getInstance() {
return instance;
}
private static ArrayList<BigClip> clips = new ArrayList<BigClip>();
private BigClip get(String name) {
for (BigClip clip : clips) {
if (clip.getName().equalsIgnoreCase(name)) return clip;
}
return null;
}
public void play(File file) {
try {
AudioInputStream audioIn = AudioSystem.getAudioInputStream(file);
BigClip clip = get(file.getName());
if (clip == null) {
BigClip newClip = new BigClip(file.getName());
clips.add(newClip);
clip = newClip;
}
clip.open(audioIn);
clip.start();
}
catch (Exception e) { e.printStackTrace(); }
}
}
However, when I try to run it using:
AudioPlayer.getInstance().play(new File("audio/people/blacksmith/blacksmith01a_new.wav"));
I get the following stack trace:
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1170)
at me.pogostick29.audiorpg.audio.AudioPlayer.play(AudioPlayer.java:38)
at me.pogostick29.audiorpg.person.people.Blacksmith.playDialogue(Blacksmith.java:12)
at me.pogostick29.audiorpg.AudioRPG.main(AudioRPG.java:33)
Here's the format I used when exporting the file with Audition.
Nevermind, I fixed it by using this library: http://www.javazoom.net/javalayer/javalayer.html
I'm making a game which is using sound and images. The weirdest thing is happening. When I load sound, my image won't appear. However, when I don't load my sound, my image does appear. Here is my code:
package com.gbp.chucknorris;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class Title extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
public Thread thread;
private BufferedImage logo;
private Clip clip, titleClip;
public Title() {
super();
loadSound();
loadImages();
bind();
setBackground(Color.WHITE);
}
private void loadSound() {
File f = new File("res/sounds/title.wav");
AudioInputStream stream = null;
try {
stream = AudioSystem.getAudioInputStream(f);
} catch (UnsupportedAudioFileException | IOException e) {
e.printStackTrace();
}
DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat());
try {
clip = (Clip) AudioSystem.getLine(info);
} catch (LineUnavailableException e) {
e.printStackTrace();
}
try {
clip.open(stream);
} catch (LineUnavailableException | IOException e) {
e.printStackTrace();
}
File title = new File("res/sounds/theme.wav");
AudioInputStream titleStream = null;
try {
titleStream = AudioSystem.getAudioInputStream(title);
} catch (UnsupportedAudioFileException | IOException e) {
e.printStackTrace();
}
DataLine.Info titleInfo = new DataLine.Info(Clip.class, titleStream.getFormat());
try {
titleClip = (Clip) AudioSystem.getLine(titleInfo);
titleClip.open(titleStream);
} catch (LineUnavailableException | IOException e) {
e.printStackTrace();
}
titleClip.loop(Clip.LOOP_CONTINUOUSLY);
}
private void bind() {
InputMap im = getInputMap();
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke("DOWN"), "down");
am.put("down", new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
}
});
}
private void loadImages() {
try {
logo = ImageIO.read(new File("res/pics/MenuPanel.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while (true) {
repaint();
}
}
public void addNotify() {
super.addNotify();
thread = new Thread(this);
thread.start();
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(logo, 0, 0, null);
}
}
Thanks in advance!
You need to learn to use background threading such as a SwingWorker so as not to tie up the event thread, the EDT, when loading and playing sounds. You can read up on how to use this here: Lesson: Concurrency in Swing.
Edit: I wouldn't recommend doing this:
#Override
public void run() {
while (true) {
repaint();
}
}
I am trying to read a log file continuously where the logs are being written ,both the processes are happening simultaneously.I am using rolling file appender for generating logs but the problem is ,when the file is about to change sometimes the data written when the file is nearing end is not read.Here is my code that generates log file continuously.
import java.util.Timer;
import java.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class Slf4jSample {
static Logger logger = LoggerFactory.getLogger(Slf4jSample.class);
public static void main(final String[] args) {
int delay = 0; // delay for 5 sec.
int period = 1000; // repeat every sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
int i = 0;
public void run() {
// Task here ...
for (i = 0; i < 50; i++) {
logger.error("testing" + i);
System.out.println(i);
}
}
}, delay, period);
}
}
and here is my code that is reading it continuously.
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.mobility.config.ParseConfig;
import com.mobility.mail.SendMail;
import com.mobility.vo.ConfigurationVO;
import com.mobility.vo.LogVO;
import javax.mail.*;
TimerTask fileWatcherTask = new LogWatcher(fileName) {
long addFileLen = fileName.length();
FileChannel channel, oldChannel;
FileLock lock, oldLock;
#Override
protected void onChange(File file) {
RandomAccessFile access = null;
RandomAccessFile oldAccess = null;
int level = 0;
try {
access = new RandomAccessFile(file, "rw");
oldAccess = new RandomAccessFile(prevFileName, "rw");
channel = access.getChannel();
lock = channel.lock();
oldChannel = oldAccess.getChannel();
oldLock = oldChannel.lock();
// System.out.println("addFileLen>>" + addFileLen);
if (file.length() <= addFileLen) {
System.out.println("in if>>");
// reading old file
if (prevFileName.exists()) {
parsingLog(oldAccess, addFileLen,level);
addFileLen = file.length();
}
// reading old file ends
// Seek to 0th position when the file changes.
parsingLog(access, 0,level);
} else {
// access.seek(addFileLen);
parsingLog(access, addFileLen,level);
System.out.println("else>>>");
addFileLen = file.length();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
lock.release();
oldLock.release();
} catch (IOException e1) {
e1.printStackTrace();
} // Close the file
try {
channel.close();
oldChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Timer timer = new Timer();
// repeat the check every second
long scheduleTimer = Long.parseLong(properties
.getProperty("scheduler.timer"));
timer.schedule(fileWatcherTask, new Date(), scheduleTimer);
}
}
public void parsingLog(RandomAccessFile access, long fileLength, int level) {
List<String> logList = new ArrayList<String>();
int flag = 0;
String line = null;
try {
access.seek(fileLength);
while ((line = access.readLine()) != null) {
System.out.println("after reading line >"+line);
}
}catch(Exception e){
}
}
PS:it doesn't read the contents when it is nearing end.
I would open the file until it has been fully read and only close it when you have finished reading it. This may require your logger to create a new file each time, but you are unlikely to miss anything this way.