I'm trying to make music play with one button(First click is play, second is stop, third is play again etc etc). The problem is it does not want to stop. Second click is blank and then third music starts to impose itself. Any suggestions?
public void music() {
File file = new File("music.wav");
AudioInputStream audioStream = null;
Clip clip = null;
try {
audioStream = AudioSystem.getAudioInputStream(file);
clip = AudioSystem.getClip();
clip.open(audioStream);
} catch (LineUnavailableException e) {
throw new RuntimeException(e);
} catch (UnsupportedAudioFileException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (m % 2 == 1) {
clip.start();
m++;
} else {
clip.stop();
m++;
}
}
public void playmusic() {
if(m%2==1) {
File file = new File("music.wav");
AudioInputStream audioStream = null;
try {
audioStream = AudioSystem.getAudioInputStream(file);
clip = AudioSystem.getClip();
clip.open(audioStream);
} catch (LineUnavailableException e) {
throw new RuntimeException(e);
} catch (UnsupportedAudioFileException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
clip.start();
m++;
}
else {
clip.stop();
m++;
}
}
I did it like this, thanks for helping Karl. To be honest it still feels overly complicated. I just don't know the tools to do it better.
Related
This is my sound class.
public class Sounds extends Thread {
private String filename;
private Position curPosition;
private final int EXTERNAL_BUFFER_SIZE = 524288;
enum Position {
LEFT, RIGHT, NORMAL
};
public Sounds(String wavFile) {
filename = wavFile;
curPosition = Position.NORMAL;
}
public Sounds(String wavfile, Position p) {
filename = wavfile;
curPosition = p;
}
public void run() {
File soundFile = new File(filename);
if (!soundFile.exists()) {
System.err.println(".wav 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();
}
}
}
And this is my ActionListener that I want to stop the music when the user clicks a button. The music plays on start up.
btnSound.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
btnSound.setVisible(false);
btnNoSound.setVisible(true);
new Sounds("Sounds/MenuMusic.wav").end();
}
});
I can get the music to play just fine, but I can't figure out how to stop it. I tried using .stop() and .end() but I was told they were deprecated. Anyone have any idea how I can do this? thanks.
You could use the clip class. This is my code for reading a .wav file and playing it:
try {
File file = new File(src); // src is the location of the file
AudioInputStream stream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(stream);
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
That was, clip.stop() will stop the clip. To reset the clip, use clip.setFramePosition(0). Note that clip does not need to be closed, because if clip.close() is called after clip.start(), the clip will not play.
Hope that's what you were looking for!
EDIT: Scoping
Using scoping in Java, if you declare a local variable in a method, you cannot access it outside of the method. If you want to access the clip outside of the main method, extract it to a field:
class Main {
static Clip clip;
public static void main (String... args) {
try {
File file...
clip = AudioSystem.getClip();
...
} catch...
}
}
I'm getting an exception ONLY when the program is run with a jar file. When I run it through IntelliJ i don't get the exception. Here's my code:
opening the SourceDataLine (clip is an InputStream):
Frmt = new AudioFormat(44100, 16, 2, true, false);
Info = new DataLine.Info(SourceDataLine.class, Frmt);
Bfr = new byte[409600];
NBToRead = 409600;
try
{
LineIn = (SourceDataLine) AudioSystem.getLine(Info);
LineIn.open(Frmt);
TotalToRead = Clip.available();
}
catch (LineUnavailableException e)
{
e.printStackTrace();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
playing the audio:
LineIn.start();
try
{
while (Total < TotalToRead && !Stopped)
{
NBRead = Clip.read(Bfr, 0, NBToRead);
if (NBRead == -1)
{
break;
}
Total += NBRead;
LineIn.write(Bfr, 0, NBRead);
}
}
catch (IOException e)
{
e.printStackTrace();
}
LineIn.stop();
I'm getting an IllegalArgumentException on this line:
LineIn.write(Bfr, 0, NBRead);
I am developing a drum metronome. So I have .wav sound files and I need to play them with using minimum computer memory and CPU because it's very important for the metronome to play the sample on the exact time. Currently I use the code from this link
How to play .wav files with java
class MakeSound {
private final int BUFFER_SIZE = 128000;
private File soundFile;
private AudioInputStream audioStream;
private AudioFormat audioFormat;
private SourceDataLine sourceLine;
/**
* #param filename the name of the file that is going to be played
*/
public void playSound(String filename){
String strFilename = filename;
try {
soundFile = new File(strFilename);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
try {
audioStream = AudioSystem.getAudioInputStream(soundFile);
} catch (Exception e){
e.printStackTrace();
System.exit(1);
}
audioFormat = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
try {
sourceLine = (SourceDataLine) AudioSystem.getLine(info);
sourceLine.open(audioFormat);
} catch (LineUnavailableException e) {
e.printStackTrace();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
sourceLine.start();
int nBytesRead = 0;
byte[] abData = new byte[BUFFER_SIZE];
while (nBytesRead != -1) {
try {
nBytesRead = audioStream.read(abData, 0, abData.length);
} catch (IOException e) {
e.printStackTrace();
}
if (nBytesRead >= 0) {
#SuppressWarnings("unused")
int nBytesWritten = sourceLine.write(abData, 0, nBytesRead);
}
}
sourceLine.drain();
sourceLine.close();
}
}
This code works but it's too slow for using it in a metronome app. So which is the fastest way of playing wav sound files. Please take into account that sometimes I need to play them simultaneously so the sound should play as a separate thread I think.
Thanks
i am assuming that you have a working method that looks like this:
example #1: (don't do this)
public void startMetronome(){
boolean abort = false;
String audoFileName = new String("myAudioFile);
do{
playSound(audoFileName );
while(abort != false);
}
or maybe you've done some better implementation like this:
exapmle#2: (don't do this either)
Runnable r = new Runnable(){
boolean abort = false;
String audoFileName = new String("myAudioFile);
do{
playSound(audoFileName );
try{
Thread.sleep(500);
}catch (Exception e);
while(abort != false);
}
new Thread(r).start();
in any case you're doing a big mistake: you initialize every time you play a sound the sound line and every time you load the file again and again.
but thats a toally wrong approach, you have to load the file once, open the line once and play the sound repetially on the line!
(cheap) solution #3:
adjust your playSoundmethode like this:
public void playSound(String filename){
//same as above
String strFilename = filename;
soundFile = new File(strFilename); //i've shorened the catch/throws, to make it more readable
audioStream = AudioSystem.getAudioInputStream(soundFile);
audioFormat = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
sourceLine = (SourceDataLine) AudioSystem.getLine(info);
sourceLine.open(audioFormat);
sourceLine.start();
//right now, the line is set up and all data is availible
boolean isRunning = true;
while(isRunning){ //this is an endless loop!
int nBytesRead = 0;
byte[] abData = new byte[BUFFER_SIZE];
while (nBytesRead != -1) {
nBytesRead = audioStream.read(abData, 0, abData.length);
//and your timing here
try{
Thread.sleep(500);
}catch (Exception e);
}
sourceLine.drain();
sourceLine.close();
}
and best practice would be to play the whole thing in an seperate thread... (as example #2)
I know about the clip.stop() method, however it doesn't seem to work within when I have it inside the key_events. It just causes an Error. Well I know why it causes the error. Because I'm asking it to essentially stop a clip that doesn't exist until a few lines later. But using this same logic or close to it if possible, how could I recode that so it knows to select the previous clip that was playing from a previous key_event. The functionality I'm intending for is: When F1 is pressed, a wav plays. When F2 is pressed, current wav STOPS, new wav STARTS. When F3 is pressed, current wav STOPS, new wav STARTS. Etc etc etc.
case KeyEvent.VK_F1:
try {
//stop any sound
clip.stop();
sample = AudioSystem.getAudioInputStream(getURL(filename));
//create a sound buffer
Clip clip = AudioSystem.getClip();
//load the audio file
clip.open(sample);
//play sample
clip.start();
} catch (MalformedURLException ez) {
} catch (IOException ez) {
} catch (LineUnavailableException ez) {
} catch (UnsupportedAudioFileException ez) {
} catch (Exception ez) { }
break;
case KeyEvent.VK_F2:
try {
//stop any sound
clip.stop();
sample = AudioSystem.getAudioInputStream(getURL(filename2));
//create a sound buffer
Clip clip = AudioSystem.getClip();
//load the audio file
clip.open(sample);
//play sample
clip.start();
} catch (MalformedURLException ez) {
} catch (IOException ez) {
} catch (LineUnavailableException ez) {
} catch (UnsupportedAudioFileException ez) {
} catch (Exception ez) { }
break;
case KeyEvent.VK_F3:
try {
//stop any sound
clip.stop();
sample = AudioSystem.getAudioInputStream(getURL(filename3));
//create a sound buffer
Clip clip = AudioSystem.getClip();
//load the audio file
clip.open(sample);
//play sample
clip.start();
} catch (MalformedURLException ez) {
} catch (IOException ez) {
} catch (LineUnavailableException ez) {
} catch (UnsupportedAudioFileException ez) {
} catch (Exception ez) { }
break;
case KeyEvent.VK_F4:
try {
//stop any sound
clip.stop();
sample = AudioSystem.getAudioInputStream(getURL(filename4));
//create a sound buffer
Clip clip = AudioSystem.getClip();
//load the audio file
clip.open(sample);
//play sample
clip.start();
} catch (MalformedURLException ez) {
} catch (IOException ez) {
} catch (LineUnavailableException ez) {
} catch (UnsupportedAudioFileException ez) {
} catch (Exception ez) { }
break;
case KeyEvent.VK_F5:
try {
//stop any sound
clip.stop();
sample = AudioSystem.getAudioInputStream(getURL(filename5));
//create a sound buffer
Clip clip = AudioSystem.getClip();
//load the audio file
clip.open(sample);
//play sample
clip.start();
} catch (MalformedURLException ez) {
} catch (IOException ez) {
} catch (LineUnavailableException ez) {
} catch (UnsupportedAudioFileException ez) {
} catch (Exception ez) { }
break;
case KeyEvent.VK_F6:
try {
//stop any sound
clip.stop();
sample = AudioSystem.getAudioInputStream(getURL(filename6));
//create a sound buffer
Clip clip = AudioSystem.getClip();
//load the audio file
clip.open(sample);
//play sample
clip.start();
} catch (MalformedURLException ez) {
} catch (IOException ez) {
} catch (LineUnavailableException ez) {
} catch (UnsupportedAudioFileException ez) {
} catch (Exception ez) { }
break;
case KeyEvent.VK_F7:
try {
//stop any sound
clip.stop();
sample = AudioSystem.getAudioInputStream(getURL(filename7));
//create a sound buffer
Clip clip = AudioSystem.getClip();
//load the audio file
clip.open(sample);
//play sample
clip.start();
} catch (MalformedURLException ez) {
} catch (IOException ez) {
} catch (LineUnavailableException ez) {
} catch (UnsupportedAudioFileException ez) {
} catch (Exception ez) { }
break;
Any help would be greatly appreciated :) Thanks
It's difficult to be 100% sure, but it looks like you are shadowing your variables...
clip.stop();
sample = AudioSystem.getAudioInputStream(getURL(filename));
//create a sound buffer
Clip clip = AudioSystem.getClip();
In fact, I'm not even sure how this would compile...
Define Clip as an instance variable, when you program is initialised, initialise the Clip at the same time.
You should be able to call stop at any time, but this will only reset the Clip back to the start of the current input. What you need to, also do, is close the Clip, which releases the internal resources been managed by the Clip for the current input...
KeyListeners are also notoriously troublesome and you should consider using Key Bindings as they provide you with the control to determine the focus level that the key events can be generated at, for example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
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;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestPlayer {
public static void main(String[] args) {
new TestPlayer();
}
public TestPlayer() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
try {
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (LineUnavailableException exp) {
exp.printStackTrace();
}
}
});
}
public class TestPane extends JPanel {
private Clip clip;
private List<File> playList;
private int index;
private JLabel label;
public TestPane() throws LineUnavailableException {
label = new JLabel("Play stuff");
add(label);
clip = AudioSystem.getClip();
File[] files = new File("A folder of music files").listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return file.getName().toLowerCase().endsWith(".wav");
}
});
playList = new ArrayList<>(Arrays.asList(files));
index = -1;
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "previous");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "next");
ActionMap am = getActionMap();
am.put("next", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playNext();
}
});
am.put("previous", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playPrevious();
}
});
}
public void playNext() {
index++;
if (index >= playList.size()) {
index = 0;
}
File file = playList.get(index);
play(file);
}
public void playPrevious() {
index--;
if (index < 0) {
index = playList.size() - 1;
}
File file = playList.get(index);
play(file);
}
public void play(File file) {
try {
stop();
label.setText(file.getName());
AudioInputStream sample = AudioSystem.getAudioInputStream(file);
clip.open(sample);
clip.start();
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException exp) {
exp.printStackTrace();
}
}
public void stop() {
clip.stop();
clip.close();
}
}
}
I am trying to record the audio using AudioRecorde.
Though it creates file but could not record it. Please provide some inputs.
private void startRecording(){
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,44100,AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT,AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT));
try {
recorder.startRecording();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
At the time of stoprecording
private void stopRecording(){
if(null != recorder){
recorder.stop();
recorder.release();
FileOutputStream fOut = null;
try{
int buffSize = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
//ByteBuffer buffer = ByteBuffer.allocate(AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT));
byte b[] = new byte[buffSize];
recorder.read(b,0,buffSize);
//getFilename() will get the file
fOut = new FileOutputStream(getFilename());
fOut.write(b);
}catch(Exception e){
e.printStackTrace();
}finally{
if(fOut != null){
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
recorder = null;
}
}
It creates a file with buffsize but could not play it.
Here is the code for playing the file
private void startPlaying() {
mPlayer = new MediaPlayer();
if(playing){
playing = false;
}else{
try {
File myFile = new File(prevFile);
txtStatus.setText("Playing...");
imgStatus.setVisibility(View.VISIBLE);
imgStatus.setBackgroundDrawable(getResources().getDrawable(R.drawable.play_small));
if(myFile.exists()){
System.out.println("file is exist");
}else{
System.out.println("file is not exist");
}
mPlayer.setDataSource(prevFile);
System.out.println("file path is is ::> " + prevFile);
mPlayer.prepare();
mPlayer.start();
playing = true;
} catch (IOException e) {
e.printStackTrace();
write.saveToFile(getApplicationContext(), "prepare() failed"+"\n");
}
}
}