Skip to content

Commit

Permalink
Adding method that could play a sound file. No external libraries used.
Browse files Browse the repository at this point in the history
Issue - iluwatar#108
  • Loading branch information
deepikasidana committed May 4, 2022
1 parent 6b93ba9 commit cc96a00
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/main/java/media/PlaySoundSnippet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package media;

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;

/*
* 30 Seconds of Java code library
*
*/
public class PlaySoundSnippet {


/**
* Factorial. Works only for small numbers
*
* @param soundFile which needs to be played
* @throws IOException if an I/O error occurs
* @throws UnsupportedAudioFileException if the file did not contain valid data of a recognized file type and format
* @throws LineUnavailableException if a line cannot be opened because it is unavailable
*/
public static void playSound(String soundFile) throws IOException, UnsupportedAudioFileException, LineUnavailableException {
File f = new File("./" + soundFile);
AudioInputStream audioIn = null;
Clip clip = null;

try {
audioIn = AudioSystem.getAudioInputStream(f.toURI().toURL());
clip = AudioSystem.getClip();
clip.open(audioIn);

clip.start();

FloatControl volume = (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN);
volume.setValue(1.0f); // Reduce volume by 10 decibels.

clip.drain();

}
finally {
try {
clip.close();
}
catch (Exception exp) {
exp.printStackTrace();
}
}

}
}


25 changes: 25 additions & 0 deletions src/test/java/media/PlaySoundSnippetTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package media;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

/*
* Tests for 30 Seconds of Java code library
*
*/
class PlaySoundSnippetTest {
/**
* Tests for {@link PlaySoundSnippet#playSound(String)}.
*/
@Test
void playSound() {
String filename = "media/file_example_WAV_1MG.wav";

assertDoesNotThrow(() -> {
PlaySoundSnippet.playSound(filename);
});

}

}
Binary file added src/test/resources/media/file_example_WAV_1MG.wav
Binary file not shown.

0 comments on commit cc96a00

Please sign in to comment.