I have a JavaSoundRecorder that I have created as shown below. When I create an object of the class and call the finish() function the line does not stop/close and remains active (does not reach null state). Meaning that I can only make a single recording with the recorder. What can I do to fix this issue?
import java.io.*;
import javax.sound.sampled.*;
import java.util.Set;
public class JavaSoundRecorder {
private TargetDataLine line;
private AudioFileFormat.Type fileType;
private File savedWav;
private AudioFormat audioForm;
private DataLine.Info info;
public int errorNum;
public void setFile(File savedWav) {
this.savedWav = savedWav;
}
/*constructs class*/
public JavaSoundRecorder() {
fileType = AudioFileFormat.Type.WAVE;
audioForm = getAudioFormat();
info = new DataLine.Info(TargetDataLine.class, audioForm);
}
/*
* Defines an audio format
*/
AudioFormat getAudioFormat() {
float sampleRate = 16000;
int sampleSizeInBits = 16;
int channels = 1;
boolean signed = true;
boolean BigEndian = true;
AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits, channels , signed, BigEndian);
return format;
}
/*Captures the sound and records in WAV fiLE, creates a new thread for recording*/
protected int startRecording(String path) {
setFile(new File(path));
errorNum = 0;
if(line == null) {
Thread thread2 = new Thread(new Runnable() {
#Override
public void run() {
try {
//check if system supports the data line
if(!AudioSystem.isLineSupported(info)) {
System.out.println("not supported")
}
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(audioForm);
line.start();
AudioInputStream ais = new AudioInputStream(line);
//write recoding to file..
AudioSystem.write(ais, fileType, savedWav);
}
catch(LineUnavailableException e) {
errorNum = 3;
e.printStackTrace();
}
catch(IOException e) {
errorNum = 4;
e.printStackTrace();
}
}
});
thread2.start();
}
return errorNum;
}
/*stops recording*/
public void finish() {
line.stop();
line.close();
}
}
I'd look at using loose coupling pattern. The finish() method should suggest to the recording thread to do the work of closing and cleaning up, not actually do that work itself. Thus have finish() flip a boolean named something like isRunning to false. The boolean can be volatile to help ensure the change in value is immediately read across the different threads.
With this, move the code which closes and cleans up to the end of the run() method, and surround the code that executes the write() with a while(isRunning) block.
Now, I'm not up enough on the details to know off the top of my head the exact changes required, but I think you will also have to refactor a bit so the writing is an action that repeats, that repeatedly gives control back to the enclosing while() after each write operation.
So I have 3 threads,
A thread which downloads audio and the audio schedule object from the internet.
A thread which plays the audio according to the audio schedule.
And a web socket "notification" listener that listens for messages that say we have to download new audio and schedule as our current one is outdated.
The program flow is as follows:
On application startup: The ScheduleDownloader starts,downloads audio and schedule file.Once completed it needs to tell the audio player "hey the files are ready and here is the schedule" and it doesnt need to do anything for now
The audio player starts and continuously loops with no exit condition.
The web socket listener starts,when it gets a message.It should tell the schedule downloader "You need to start again as there is new files you need to download",it doesnt need to send any data to the schedule downloaded,just start it up again.The music should remain playing.Once it is done it should now restart the audio player thread with the new schedule.
Here is what I have so far,I am not sure how to get ScheduleDownloader to tell AudioPlayer "the files are ready and you need to start,here is the schedule" or "you need to restart with the new schedule,here it is" or how to get the listener to say "ScheduleDownloader you need to start again"
public class ScheduleDownloader extends Thread {
private Thread t;
private String threadName;
String username;
String password;
public ScheduleDownloader(String username,String password,String threadName){
this.username = username;
this.password = password;
this.threadName= threadName;
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}}
public void run() {
try {
Schedule schedule= null;
while(schedule == null){
System.out.println("Searching for schedule");
schedule= getTodaysSchedule();
}
System.out.println("Schedule Found");
boolean result = false;
while(result == false){
result = downloadFiles(schedule);
}
System.out.println("Files Downloaded");
} catch (IOException e) {
e.printStackTrace();
}
}
public Schedule getTodaysSchedule() throws IOException {
Schedule schedule = null;
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials
= new UsernamePasswordCredentials(username,password);
provider.setCredentials(AuthScope.ANY, credentials);
String url = "http://localhost:5000/api/schedule/today";
HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(); //Use this instead
HttpGet request = new HttpGet(url);
HttpResponse response = httpClient.execute(request);
//read content response body
if (response.getStatusLine().getStatusCode() != 200) {
System.out.println("sorry error:" + response.getStatusLine().getStatusCode());
} else {
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
//change json response to java objects
Gson gson = new Gson();
schedule = gson.fromJson(String.valueOf(result),Schedule.class);
}
return schedule;
}
public static boolean downloadFiles(Schedule schedule) {
//get the music
for(int i =0;i<schedule.getMusicScheduleItems().size();i++){
downloadOneFile("shoutloudaudio","music/" +
schedule.getMusicScheduleItems().get(i).getMusic().getId()+
"-music.wav");
}
//get the advertisements
for(int i =0;i<schedule.getAdvertisementScheduleItems().size();i++){
downloadOneFile("shoutloudaudio","advertisements/" +
schedule.getAdvertisementScheduleItems().get(i).getAdvertisement().getId()+
"-advertisement.wav");
}
return true;
}
public static boolean downloadOneFile(String bucketName,String key) {
if( new File(key.split("/")[1]).isFile()){
//check if we have it already and dont need to download it
System.out.println(key + " alraeady exits");
return true;
}
AWSCredentials awsCredentials = new BasicAWSCredentials(
"removed",
"removed"
);
AmazonS3 s3client = AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
.withRegion(Regions.EU_WEST_1)
.build();
S3Object s3object = s3client.getObject(bucketName, key);
S3ObjectInputStream inputStream = s3object.getObjectContent();
InputStream reader = new BufferedInputStream(
inputStream);
File file = new File(key.split("/")[1]);//save the file as whats after the / in key
OutputStream writer = null;
try {
writer = new BufferedOutputStream(new FileOutputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
int read = -1;
try {
while ((read = reader.read()) != -1) {
writer.write(read);
}
writer.flush();
writer.close();
}catch(IOException e){
e.printStackTrace();
return false;
}
return true;
}
}
AudioPlayer
public class AudioPlayer extends Thread {
Long currentFrameMusic;
Long currentFrameAdvertisement;
Clip clipMusic;
Clip clipAdvertisement;
private Thread t;
// current status of clip
String statusMusic;
String statusAdvertisement;
static AudioInputStream musicInputStream;
static AudioInputStream advertisementInputStream;
static String filePath;
Schedule schedule;
// constructor to initialize streams and clip
public AudioPlayer(Schedule schedule)
throws UnsupportedAudioFileException,
IOException, LineUnavailableException
{
//setup audio stream for music first
// create AudioInputStream object
this.schedule = schedule;
appendMusicFiles(schedule);
// create clip reference
clipMusic = AudioSystem.getClip();
// open audioInputStream to the clip
clipMusic.open(musicInputStream);
clipMusic.loop(Clip.LOOP_CONTINUOUSLY);
}
public void run(){
playMusic();
try {
checkShouldWePlayAnAdvertisement();
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void start(){
t = new Thread (this, "AudioPlayerThread");
t.start ();
}
public void start2() throws IOException, UnsupportedAudioFileException, LineUnavailableException, InterruptedException {
playMusic();
checkShouldWePlayAnAdvertisement();
}
public void playMusic()
{
//start the clip
clipMusic.start();
statusMusic = "play";
}
// Method to pause the audio
public void pauseMusic()
{
if (statusMusic.equals("paused"))
{
System.out.println("audio is already paused");
return;
}
this.currentFrameMusic =
this.clipMusic.getMicrosecondPosition();
clipMusic.stop();
statusMusic = "paused";
System.out.println("pausing music");
}
// Method to resume the audio
public void resumeAudioMusic() throws UnsupportedAudioFileException,
IOException, LineUnavailableException
{
if (statusMusic.equals("play"))
{
System.out.println("Audio is already "+
"being played");
return;
}
clipMusic.close();
resetAudioStreamMusic();
clipMusic.setMicrosecondPosition(currentFrameMusic);
System.out.println("resuming music");
this.playMusic();
}
// Method to restart the audio
public void restartMusic() throws IOException, LineUnavailableException,
UnsupportedAudioFileException
{
clipMusic.stop();
clipMusic.close();
resetAudioStreamMusic();
currentFrameMusic = 0L;
clipMusic.setMicrosecondPosition(0);
this.playMusic();
}
// Method to stop the audio
public void stopMusic() throws UnsupportedAudioFileException,
IOException, LineUnavailableException
{
currentFrameMusic = 0L;
clipMusic.stop();
clipMusic.close();
}
public void resetAudioStreamMusic() throws UnsupportedAudioFileException, IOException,
LineUnavailableException
{
clipMusic = AudioSystem.getClip();
appendMusicFiles(schedule);
// open audioInputStream to the clip
clipMusic.open(musicInputStream);
clipMusic.loop(Clip.LOOP_CONTINUOUSLY);
}
public static void appendMusicFiles(Schedule schedule) throws IOException, UnsupportedAudioFileException {
//add the first audio file to stream
AudioInputStream appendedFiles = AudioSystem.getAudioInputStream(
new File(schedule.getMusicScheduleItems().get(0).getMusic()
.getId() + "-music.wav"));
//loop through an combine
for(int i =1;i<schedule.getMusicScheduleItems().size();i++){
File file= new File(schedule.getMusicScheduleItems().get(i).getMusic()
.getId() + "-music.wav");
AudioInputStream toBeAppended = AudioSystem.getAudioInputStream(file);
//append them
appendedFiles =
new AudioInputStream(
new SequenceInputStream(appendedFiles, toBeAppended),
appendedFiles.getFormat(),
appendedFiles.getFrameLength() + toBeAppended.getFrameLength());
}
musicInputStream = appendedFiles;
}
//advertisement methods
public void playAdvertisements() throws LineUnavailableException, IOException, InterruptedException {
clipAdvertisement = AudioSystem.getClip();
// open audioInputStream to the clip
clipAdvertisement.open(advertisementInputStream);
System.out.println(clipAdvertisement.getMicrosecondLength());
//start the clip
clipAdvertisement.start();
Thread.sleep(clipAdvertisement.getMicrosecondLength() / 1000);
statusAdvertisement = "play";
System.out.println("playing advertisements");
}
// Method to pause the audio
public void pauseAdvertisements()
{
if (statusAdvertisement.equals("paused"))
{
System.out.println("audio is already paused");
return;
}
this.currentFrameAdvertisement =
this.clipAdvertisement.getMicrosecondPosition();
clipAdvertisement.stop();
statusAdvertisement = "paused";
}
// Method to resume the audio
public void resumeAudioAdvertisement() throws UnsupportedAudioFileException,
IOException, LineUnavailableException, InterruptedException {
if (statusAdvertisement.equals("play"))
{
System.out.println("Audio is already "+
"being played");
return;
}
clipAdvertisement.close();
resetAudioStreamAdvertisement();
clipAdvertisement.setMicrosecondPosition(currentFrameMusic);
this.playAdvertisements();
}
// Method to restart the audio
public void restartAdvertisement() throws IOException, LineUnavailableException,
UnsupportedAudioFileException, InterruptedException {
clipAdvertisement.stop();
clipAdvertisement.close();
resetAudioStreamAdvertisement();
currentFrameAdvertisement = 0L;
clipAdvertisement.setMicrosecondPosition(0);
this.playAdvertisements();
}
// Method to stop the audio
public void stopAdvertisement() throws UnsupportedAudioFileException,
IOException, LineUnavailableException, InterruptedException {
currentFrameAdvertisement = 0L;
clipAdvertisement.stop();
clipAdvertisement.close();
System.out.println("stopping advertisement");
}
public void resetAudioStreamAdvertisement() throws UnsupportedAudioFileException, IOException,
LineUnavailableException
{
advertisementInputStream = AudioSystem.getAudioInputStream(
new File(filePath).getAbsoluteFile());
clipAdvertisement.open(musicInputStream);
clipAdvertisement.loop(Clip.LOOP_CONTINUOUSLY);
}
public static void appendAdvertisementFiles(List<Advertisement> advertisementItems) throws IOException, UnsupportedAudioFileException {
//add the first audio file to stream
AudioInputStream appendedFiles = AudioSystem.getAudioInputStream(
new File(advertisementItems.get(0)
.getId() + "-advertisement.wav"));
//loop through an combine
for(int i =1;i<advertisementItems.size();i++){
File file= new File(advertisementItems.get(i)
.getId() + "-advertisement.wav");
AudioInputStream toBeAppended = AudioSystem.getAudioInputStream(file);
//append them
appendedFiles =
new AudioInputStream(
new SequenceInputStream(appendedFiles, toBeAppended),
appendedFiles.getFormat(),
appendedFiles.getFrameLength() + toBeAppended.getFrameLength());
}
advertisementInputStream = appendedFiles;
}
public void checkShouldWePlayAnAdvertisement() throws IOException, UnsupportedAudioFileException, LineUnavailableException, InterruptedException {
ArrayList<String> playedAtTimes = new ArrayList<>();
ArrayList<Advertisement> advertisementsToBePlayed = new ArrayList<>();
boolean found;
//played at times is used to keep track of what time we played advertisements
//so when the loop reruns and the time hasnt changed it doesnt play it again
while(true){
found = false;
ZonedDateTime zdt = ZonedDateTime.now();
String timeHHMM =zdt.toString().substring(11,16);
for(int i =0;i<schedule.getAdvertisementScheduleItems().size();i++)
{
if(schedule.getAdvertisementScheduleItems().get(i).getTimes()
.contains(timeHHMM))
{
//this item should be played now
if(playedAtTimes.contains(timeHHMM)){
//we already played this,but the time hasnt changed when the loop ran again
}else{
advertisementsToBePlayed.add(schedule.getAdvertisementScheduleItems().get(i).getAdvertisement());
found = true;
}
}
}
if(found== true){
playedAtTimes.add(timeHHMM);
appendAdvertisementFiles(advertisementsToBePlayed);
pauseMusic();
playAdvertisements();
stopAdvertisement();
resumeAudioMusic();
}
}
}
}
IotClient(part of listener)
public class IotClient extends Thread {
Thread t;
String username;
public IotClient(String username) {
this.username = username;
}
public void run(){
String clientEndpoint = "removve"; // replace <prefix> and <region> with your own
String clientId = "1"; // replace with your own client ID. Use unique client IDs for concurrent connections.
// AWS IAM credentials could be retrieved from AWS Cognito, STS, or other secure sources
AWSIotMqttClient client = new AWSIotMqttClient(clientEndpoint, clientId, "remove", "remove");
// optional parameters can be set before connect()
try {
client.connect();
} catch (AWSIotException e) {
e.printStackTrace();
}
AWSIotQos qos = AWSIotQos.QOS0;
AWSIotTopic topic = new MyTopic("schedule/"+ username, qos);
try {
client.subscribe(topic, true);
} catch (AWSIotException e) {
e.printStackTrace();
}
while(true){
}
}
public void start(){
if (t == null) {
t = new Thread (this, "IotClientThread");
t.start ();
}
}
MyTopic(part of listener)
public class MyTopic extends AWSIotTopic {
public MyTopic(String topic, AWSIotQos qos) {
super(topic, qos);
}
#Override
public void onMessage(AWSIotMessage message) {
System.out.println("Message recieved from topic: "+ message.getStringPayload());
}
}
Threads communicate via shared references to messages 'containers' objects in memory. That could be as simple as mere mutable field of a shared instance of some class, or more typical collection like list, map, but especially queues.
ArrayBlockingQueue is a good shared reference. There would be a queue for each message direction from one thread to another. If you had 3 threads that could truly talks to each other, you would have 3 pairs, thus 6 queues (2 for each pair). However, it is often the case that messages flow only in one direction, so you might save a few.
Now, the core of these communications is a mechanism to wait for some message (reader/consumer), and notify when a message is pushed (writer/producer).
Of course, you can learn (penty of tutorials out there) from the bottom going up, from the primitive wait/notify, or you can jump into classes like ArrayBlockingQueue which abstract the wait/notify of messages into take()/put(). I recommend starting from the bottom as things will make sense more rapidly when you meet other classes in java.util.concurrent.*
I cannot give you code, it would be largely not understandable at your level without having learned the basic of ITC (inter-thread communications).
Good learning!
PS: there are many pitfalls on the way, like thread safety, atomicity of writes, lock free algorithms, deadlocks, livelocks, starvation. Just the multi queue example above can lead to circular dependencies on message arrival, particularly when queue get full and block. This is a science!
I have the problem that after i export my java project no sound is playing.
I searched in the internet and i found that:
Main.class.getResourceAsStream("fileloc");solves that problem
But my class uses this..
Where is the problem?
public class Sounds {
private static Clip eat;
public static Clip collect;
private static Clip lsd;
private static AudioInputStream inputStream;
private static FloatControl gainControl;
public static void getSounds(){
try{
eat = getClip("/sound/collect/eat.wav");
collect = getClip("/sound/collect/collect.wav");
lsd = getClip("/sound/LSD.wav");
} catch(LineUnavailableException | UnsupportedAudioFileException| IOException e){
e.printStackTrace();
}
}
private static Clip getClip(String loc) throws LineUnavailableException, UnsupportedAudioFileException, IOException{
Clip c = AudioSystem.getClip();
inputStream = AudioSystem.getAudioInputStream(Spielfeld.class.getResourceAsStream(loc));
c.open(inputStream);
gainControl = (FloatControl) c.getControl(FloatControl.Type.MASTER_GAIN);
gainControl.setValue(+6.0f);
c.setMicrosecondPosition(0);
return c;
}
public static void playSound(final String url) {
switch(url){
case "collect/collect.wav": collect.start(); collect.setMicrosecondPosition(0); break;
case "collect/eat.wav": eat.start(); eat.setMicrosecondPosition(0); break;
case "LSD.wav": lsd.start(); lsd.setMicrosecondPosition(0); break;
}
}
}
Thank you for your help
No sound after export to jar
Thank you trinityalps ;) (https://stackoverflow.com/users/5012832/trinityalps)
I have some questions about playing sound in Java and I hope you can help me out.
1. How can I stop a playing sound with a "Stop" button?
2. How can I slow down (or cooldown time) a sound?
3. I want to create a option frame where I can adjust volume and have mute option, how can I do that?
This is my code:
private void BGM() {
try {
File file = new File(AppPath + "\\src\\BGM.wav");
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(file));
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
Any help will be greatly appreciated, and, Have a nice day!
You're working in an Object Oriented programming lanuage, so let's take advantage of that and encapsulate the management of the clip/audio into a simple class...
public class AudioPlayer {
private Clip clip;
public AudioPlayer(URL url) throws IOException, LineUnavailableException, UnsupportedAudioFileException {
clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(url.openStream()));
}
public boolean isPlaying() {
return clip != null && clip.isRunning();
}
public void play() {
if (clip != null && !clip.isRunning()) {
clip.start();
}
}
public void stop() {
if (clip != null && clip.isRunning()) {
clip.stop();
}
}
public void dispose() {
try {
clip.close();
} finally {
clip = null;
}
}
}
Now, to use it, you need to create a class instance field which will allow you to access the value from anywhere within the class you want to use it...
private AudioPlayer bgmPlayer;
Then, when you need it, you create an instance of AudioPlayer and assign it to this variable
try {
bgmPlayer = new AudioPlayer(getClass().getResource("/BGM.wav"));
} catch (IOException | LineUnavailableException | UnsupportedAudioFileException ex) {
ex.printStackTrace();
}
Now, when you need to, you simply call bgmPlayer.play() or bgmPlayer.stop()
I'm trying to build a game that uses sound effects. I haven't dealt with the Java API before so I may be making some mistakes. That said though, the effects work great — my only problem is that I get a strange buzzing sound for maybe a second whenever my program exits.
Any idea how I might get rid of it? Right now I'm trying to kill any playing sounds just before the exit takes place with the killLoop() method, but that isn't getting me anywhere.
I'd appreciate your help!
public class Sound
{
private AudioInputStream audio;
private Clip clip;
public Sound(String location)
{
try {
audio = AudioSystem.getAudioInputStream(new File(location));
clip = AudioSystem.getClip();
clip.open(audio);
}
catch(UnsupportedAudioFileException uae) {
System.out.println(uae);
}
catch(IOException ioe) {
System.out.println(ioe);
}
catch(LineUnavailableException lua) {
System.out.println(lua);
}
}
public void play()
{
clip.setFramePosition(0);
clip.start();
}
public void loop()
{
clip.loop(clip.LOOP_CONTINUOUSLY);
}
public void killLoop()
{
clip.stop();
clip.close();
}
}
public class Athenaeum
{
public static void main(String[] args) throws IOException
{
final Game game = new Game();
GUI athenaeumGui = new GUI(game);
athenaeumGui.setSize(GUI.FRAME_WIDTH, GUI.FRAME_HEIGHT);
athenaeumGui.setTitle("Athenaeum");
athenaeumGui.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
athenaeumGui.setLocationRelativeTo(null);
athenaeumGui.setMinimumSize(new Dimension(GUI.FRAME_WIDTH, GUI.FRAME_HEIGHT));
athenaeumGui.buildGui();
athenaeumGui.setVisible(true);
athenaeumGui.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we)
{
game.killAudio(); // method calls Sound.killLoop()
System.exit(0);
}
});
}
}
In Java api, they say that the AudioInputStream class has a ".close()" method that "Closes this audio input stream and releases any system resources associated with the stream". Maybe this is something you can try.