Play sound with java

Java sound example: How to play a sound file in Java

My Java sound/audio example: I’m working on a simple «meditation» application that plays a sound after a certain period of time (the sound of a gong), so I thought I’d share some source code out here that demonstrates how to play a sound file in a Java application like this.

(Note: I initially found this technique described at JavaWorld.com, but the code below is taken from my project.)

In this case the sound file I’m going to play is an «au» file, but I believe this same technique works with most other sound file types as well.

A simple Java «play sound file» example

Here’s the source code for my Java sound file example:

import java.io.*; import sun.audio.*; /** * A simple Java sound file example (i.e., Java code to play a sound file). * AudioStream and AudioPlayer code comes from a javaworld.com example. * @author alvin alexander, devdaily.com. */ public class JavaAudioPlaySoundExample < public static void main(String[] args) throws Exception < // open the sound file as a Java input stream String gongFile = "/Users/al/DevDaily/Projects/MeditationApp/resources/gong.au"; InputStream in = new FileInputStream(gongFile); // create an audiostream from the inputstream AudioStream audioStream = new AudioStream(in); // play the audio clip with the audioplayer class AudioPlayer.player.start(audioStream); >>

As you can see from this source code, it’s pretty easy to create a basic Java sound file player.

My «real world» Java sound file code

I tried to make that example very simple so you can just copy that source code and run it, but my actual code is a little bit different, primarily because I need to read my sound file out of a jar file, instead of reading it as a file on a filesystem.

Читайте также:  Новое окно

For the sake of completeness, here’s the actual method from my current Java application that plays the sound file by reading the file as a resource from the jar file I create when I build my application:

private void playSound() < try < // get the sound file as a resource out of my jar file; // the sound file must be in the same directory as this class file. // the input stream portion of this recipe comes from a javaworld.com article. InputStream inputStream = getClass().getResourceAsStream(SOUND_FILENAME); AudioStream audioStream = new AudioStream(inputStream); AudioPlayer.player.start(audioStream); >catch (Exception e) < // a special way i'm handling logging in this application if (debugFileWriter!=null) e.printStackTrace(debugFileWriter); >>

As you can see from that Java code, after I retrieve the sound file from my jar file, the process of playing the sound file is the same in this code as it was in my earlier example.

Java sound/audio API

As I mentioned, I’m just learning about the Java Sound/Audio API capabilities, but it’s interesting that these classes come from the sun.audio package (instead of something like a java.sound package). As I’ve tried to find more Java sound examples, and the Javadoc for the classes I used above, I see there’s a javax.sound package that may have power than these classes, while using these two classes seems very simple. So much to learn .

In the meantime, here are a few great Java sound file links I’ve discovered on this short journey:

The complete Java sound file application

If you’d like the complete source code for this Java «play sound file» application, along with the Ant build script that is used to build the application on a Mac OS X system, it’s available here as my free, complete Java Mac (Swing) application.

Читайте также:  Product detail template html

Источник

Воспроизведение звука в Java

Нормальной русскоязычной информации по теме просто нет. Java-tutorials тоже оставляют желать лучшего. А архитектура javax.sound.sampled хоть и проста, но далеко не тривиальна. Поэтому свой первый пост на Хабре я решил посвятить именно этой теме. Приступим:

Воспроизведение звука

try < File soundFile = new File("snd.wav"); //Звуковой файл //Получаем AudioInputStream //Вот тут могут полететь IOException и UnsupportedAudioFileException AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile); //Получаем реализацию интерфейса Clip //Может выкинуть LineUnavailableException Clip clip = AudioSystem.getClip(); //Загружаем наш звуковой поток в Clip //Может выкинуть IOException и LineUnavailableException clip.open(ais); clip.setFramePosition(0); //устанавливаем указатель на старт clip.start(); //Поехали. //Если не запущено других потоков, то стоит подождать, пока клип не закончится //В GUI-приложениях следующие 3 строчки не понадобятся Thread.sleep(clip.getMicrosecondLength()/1000); clip.stop(); //Останавливаем clip.close(); //Закрываем >catch (IOException | UnsupportedAudioFileException | LineUnavailableException exc) < exc.printStackTrace(); >catch (InterruptedException exc) <> 
Регулятор громкости

Поигравшись со звуками, вы наверняка захотите иметь возможность программно изменять громкость звука. Java Sound API предоставляет такую возможность с фирменной кривотой.

//Получаем контроллер громкости FloatControl vc = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); //Устанавливаем значение //Оно должно быть в пределах от vc.getMinimum() до vc.getMaximum() vc.setValue(5); //Громче обычного 

Этот код нужно поместить между строчками clip.open(ais) и clip.setFramePosition(0).

Упрощаем процесс

import java.io.File; import java.io.IOException; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.FloatControl; import javax.sound.sampled.LineEvent; import javax.sound.sampled.LineListener; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; public class Sound implements AutoCloseable < private boolean released = false; private AudioInputStream stream = null; private Clip clip = null; private FloatControl volumeControl = null; private boolean playing = false; public Sound(File f) < try < stream = AudioSystem.getAudioInputStream(f); clip = AudioSystem.getClip(); clip.open(stream); clip.addLineListener(new Listener()); volumeControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); released = true; >catch (IOException | UnsupportedAudioFileException | LineUnavailableException exc) < exc.printStackTrace(); released = false; close(); >> // true если звук успешно загружен, false если произошла ошибка public boolean isReleased() < return released; >// проигрывается ли звук в данный момент public boolean isPlaying() < return playing; >// Запуск /* breakOld определяет поведение, если звук уже играется Если breakOld==true, о звук будет прерван и запущен заново Иначе ничего не произойдёт */ public void play(boolean breakOld) < if (released) < if (breakOld) < clip.stop(); clip.setFramePosition(0); clip.start(); playing = true; >else if (!isPlaying()) < clip.setFramePosition(0); clip.start(); playing = true; >> > // То же самое, что и play(true) public void play() < play(true); >// Останавливает воспроизведение public void stop() < if (playing) < clip.stop(); >> public void close() < if (clip != null) clip.close(); if (stream != null) try < stream.close(); >catch (IOException exc) < exc.printStackTrace(); >> // Установка громкости /* x долже быть в пределах от 0 до 1 (от самого тихого к самому громкому) */ public void setVolume(float x) < if (x<0) x = 0; if (x>1) x = 1; float min = volumeControl.getMinimum(); float max = volumeControl.getMaximum(); volumeControl.setValue((max-min)*x+min); > // Возвращает текущую громкость (число от 0 до 1) public float getVolume() < float v = volumeControl.getValue(); float min = volumeControl.getMinimum(); float max = volumeControl.getMaximum(); return (v-min)/(max-min); >// Дожидается окончания проигрывания звука public void join() < if (!released) return; synchronized(clip) < try < while (playing) clip.wait(); >catch (InterruptedException exc) <> > > // Статический метод, для удобства public static Sound playSound(String path) < File f = new File(path); Sound snd = new Sound(f); snd.play(); return snd; >private class Listener implements LineListener < public void update(LineEvent ev) < if (ev.getType() == LineEvent.Type.STOP) < playing = false; synchronized(clip) < clip.notify(); >> > > > 

Пользоваться очень просто, например:

Sound.playSound("sounds/hello.wav").join(); 

Форматы

Пару слов о поддержке форматов звуковых файлов: забудьте про mp3 и вспомните wav. Также поддерживаются au и aif.

Источник

Оцените статью