下面列出了javax.sound.sampled.AudioSystem#getClip ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private Clip GetAudioClip(String path)
{
File audioFile = new File(path);
if (!audioFile.exists())
{
return null;
}
try (AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile))
{
Clip audioClip = AudioSystem.getClip();
audioClip.open(audioStream);
FloatControl gainControl = (FloatControl) audioClip.getControl(FloatControl.Type.MASTER_GAIN);
float gainValue = (((float) config.volume()) * 40f / 100f) - 35f;
gainControl.setValue(gainValue);
return audioClip;
}
catch (IOException | LineUnavailableException | UnsupportedAudioFileException e)
{
log.warn("Error opening audiostream from " + audioFile, e);
return null;
}
}
/**
* Creates a clip from the passed sound file and plays it. If the clip
* is currently playing then the method returns, get the clip with
* {@link #getClip()} to control it.
*
* @param file
* @param loopCount
*/
public void playClip(File file, int loopCount) {
if (file == null)
return;
try {
if ((this.clip == null) || !file.getAbsolutePath().equals(this.oldFile)) {
this.oldFile = file.getAbsolutePath();
this.clip = AudioSystem.getClip();
this.clip.open(AudioSystem.getAudioInputStream(file));
}
if (this.clip.isActive())
return;
// clip.stop(); << Alternative
this.clip.setFramePosition(0);
this.clip.loop(loopCount);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* {@inheritDoc}
*/
protected boolean putToDatabase(final Chunk chunk, final int resnum) {
final InputStream aiffStream =
new MemoryAccessInputStream(chunk.getMemoryAccess(), 0,
chunk.getSize() + Chunk.CHUNK_HEADER_LENGTH);
try {
final AudioFileFormat aiffFormat =
AudioSystem.getAudioFileFormat(aiffStream);
final AudioInputStream stream = new AudioInputStream(aiffStream,
aiffFormat.getFormat(), (long) chunk.getSize());
final Clip clip = AudioSystem.getClip();
clip.open(stream);
sounds.put(resnum, new DefaultSoundEffect(clip));
return true;
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
private void play(String wavPath, float db) {
if (!dnd && db > -40) {
ClassLoader classLoader = getClass().getClassLoader();
try (AudioInputStream stream = AudioSystem.getAudioInputStream(classLoader.getResource(wavPath))) {
Clip clip = AudioSystem.getClip();
clip.open(stream);
if (db != 0.0) {
FloatControl gainControl =
(FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
gainControl.setValue(db);
}
clip.start();
} catch (Exception e) {
logger.error("Cannot start playing wav file: ", e);
}
}
}
static public void playSound(String url) {
if (url.isEmpty()) return;
try {
Clip clip = AudioSystem.getClip();
BufferedInputStream x = new BufferedInputStream(new FileInputStream(url));
AudioInputStream inputStream = AudioSystem.getAudioInputStream(x);
clip.open(inputStream);
clip.start();
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getMessage());
}
}
private static void play(String file)
{
File f = new File(file);
if(f.canRead())
{
try
{
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(f);
clip.open(inputStream);
clip.start();
}
catch(Exception e)
{
//Do nothing
}
}
}
static Clip createClip(final AudioInputStream inputStream) {
Clip clip = null;
try {
clip = AudioSystem.getClip();
clip.open(inputStream);
} catch (final LineUnavailableException | IOException e) {
e.printStackTrace();
}
return clip;
}
/**
* Creates a clip from the passed sound file and plays it. If the clip
* is currently playing then the method returns, get the clip with
* {@link #getClip()} to control it.
*
* @param file
* @param loopCount
*/
public void playClip(File file, int loopCount) {
if (file == null) {
return;
}
try {
if ((this.clip == null)
|| !file.getAbsolutePath().equals(this.oldFile)) {
this.oldFile = file.getAbsolutePath();
this.clip = AudioSystem.getClip();
this.clip.open(AudioSystem.getAudioInputStream(file));
}
if (this.clip.isActive()) {
return;
}
// clip.stop(); << Alternative
this.clip.setFramePosition(0);
this.clip.loop(loopCount);
} catch (Exception e) {
// swallow
}
}
public static void playSoundFile(String key) {
try {
if (!mudclient.optionSoundDisabled) {
File sound = mudclient.soundCache.get(key + ".wav");
if (sound == null)
return;
try {
// PC sound code:
final Clip clip = AudioSystem.getClip();
clip.addLineListener(myLineEvent -> {
if (myLineEvent.getType() == LineEvent.Type.STOP)
clip.close();
});
clip.open(AudioSystem.getAudioInputStream(sound));
clip.start();
// Android sound code:
//int dataLength = DataOperations.getDataFileLength(key + ".pcm", soundData);
//int offset = DataOperations.getDataFileOffset(key + ".pcm", soundData);
//clientPort.playSound(soundData, offset, dataLength);
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (RuntimeException var6) {
throw GenUtil.makeThrowable(var6, "client.SC(" + "dummy" + ',' + (key != null ? "{...}" : "null") + ')');
}
}
private synchronized void playCustomSound()
{
long currentMTime = NOTIFICATION_FILE.exists() ? NOTIFICATION_FILE.lastModified() : CLIP_MTIME_BUILTIN;
if (clip == null || currentMTime != lastClipMTime || !clip.isOpen())
{
if (clip != null)
{
clip.close();
}
try
{
clip = AudioSystem.getClip();
}
catch (LineUnavailableException e)
{
lastClipMTime = CLIP_MTIME_UNLOADED;
log.warn("Unable to play notification", e);
Toolkit.getDefaultToolkit().beep();
return;
}
lastClipMTime = currentMTime;
if (!tryLoadNotification())
{
Toolkit.getDefaultToolkit().beep();
return;
}
}
// Using loop instead of start + setFramePosition prevents a the clip
// from not being played sometimes, presumably a race condition in the
// underlying line driver
clip.loop(1);
}
/**
* This method allows to actually play the sound provided from the
* {@link #audioInputStream}
*
* @throws LineUnavailableException
* if the {@link Clip} object can't be created
* @throws IOException
* if the audio file can't be find
*/
protected void play() throws LineUnavailableException, IOException {
final Clip clip = AudioSystem.getClip();
clip.addLineListener(listener);
clip.open(audioInputStream);
try {
clip.start();
listener.waitUntilDone();
} catch (final InterruptedException e) {
e.printStackTrace();
} finally {
clip.close();
}
audioInputStream.close();
}
/**
* Play a wav file. Must be mono, from 8kHz to 48kHz, and 8-bit or 16-bit.
*
* @param file the 8-bit or 16-bit PWM (WAV) sample file
*/
public void playSample(final File file) {
try (AudioInputStream audioIn = AudioSystem.getAudioInputStream(file.toURI().toURL())) {
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
Delay.usDelay(clip.getMicrosecondLength());
clip.close();
} catch (IOException | LineUnavailableException | UnsupportedAudioFileException e) {
LOGGER.error(e.getLocalizedMessage(), e);
throw new RuntimeException(e);
}
}
protected Clip clipFromMixer() {
try {
int mixerIndex = UI.valueInt(MIXER_INDEX);
mixerIndex = P.constrain(mixerIndex, 0, mixers.size() - 1);
Clip clip;
clip = AudioSystem.getClip(mixers.get(mixerIndex).getMixerInfo());
return clip;
} catch (LineUnavailableException e) {
e.printStackTrace();
return null;
}
}
@Override
public Clip loadAsset( InputStream input, AssetInfo assetInfo ) throws Exception
{
AudioInputStream ais = AudioSystem.getAudioInputStream( input );
Clip clip = AudioSystem.getClip();
clip.open( ais );
return clip;
}
/**
* Loads and returns a Clip from an audio input stream.
* @param ref the resource name
* @param audioIn the audio input stream
* @param isMP3 true if MP3, false if WAV
* @return the loaded and opened clip
*/
private static MultiClip loadClip(String ref, AudioInputStream audioIn, boolean isMP3)
throws IOException, LineUnavailableException {
AudioFormat format = audioIn.getFormat();
if (isMP3) {
AudioFormat decodedFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), 16,
format.getChannels(), format.getChannels() * 2, format.getSampleRate(), false);
AudioInputStream decodedAudioIn = AudioSystem.getAudioInputStream(decodedFormat, audioIn);
format = decodedFormat;
audioIn = decodedAudioIn;
}
DataLine.Info info = new DataLine.Info(Clip.class, format);
if (AudioSystem.isLineSupported(info))
return new MultiClip(ref, audioIn);
// try to find closest matching line
Clip clip = AudioSystem.getClip();
AudioFormat[] formats = ((DataLine.Info) clip.getLineInfo()).getFormats();
int bestIndex = -1;
float bestScore = 0;
float sampleRate = format.getSampleRate();
if (sampleRate < 0)
sampleRate = clip.getFormat().getSampleRate();
float oldSampleRate = sampleRate;
while (true) {
for (int i = 0; i < formats.length; i++) {
AudioFormat curFormat = formats[i];
AudioFormat newFormat = new AudioFormat(
sampleRate, curFormat.getSampleSizeInBits(),
curFormat.getChannels(), true, curFormat.isBigEndian());
formats[i] = newFormat;
DataLine.Info newLine = new DataLine.Info(Clip.class, newFormat);
if (AudioSystem.isLineSupported(newLine) &&
AudioSystem.isConversionSupported(newFormat, format)) {
float score = 1
+ (newFormat.getSampleRate() == sampleRate ? 5 : 0)
+ (newFormat.getSampleSizeInBits() == format.getSampleSizeInBits() ? 5 : 0)
+ (newFormat.getChannels() == format.getChannels() ? 5 : 0)
+ (newFormat.isBigEndian() == format.isBigEndian() ? 1 : 0)
+ newFormat.getSampleRate() / 11025
+ newFormat.getChannels()
+ newFormat.getSampleSizeInBits() / 8;
if (score > bestScore) {
bestIndex = i;
bestScore = score;
}
}
}
if (bestIndex < 0) {
if (oldSampleRate < 44100) {
if (sampleRate > 44100)
break;
sampleRate *= 2;
} else {
if (sampleRate < 44100)
break;
sampleRate /= 2;
}
} else
break;
}
if (bestIndex >= 0)
return new MultiClip(ref, AudioSystem.getAudioInputStream(formats[bestIndex], audioIn));
// still couldn't find anything, try the default clip format
return new MultiClip(ref, AudioSystem.getAudioInputStream(clip.getFormat(), audioIn));
}
/**
* Loads and returns a Clip from an audio input stream.
* @param ref the resource name
* @param audioIn the audio input stream
* @return the loaded and opened clip
*/
private static MultiClip loadClip(String ref, AudioInputStream audioIn)
throws IOException, LineUnavailableException {
AudioFormat format = audioIn.getFormat();
String encoding = format.getEncoding().toString();
if (encoding.startsWith("MPEG")) {
// decode MP3
AudioFormat decodedFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), 16,
format.getChannels(), format.getChannels() * 2, format.getSampleRate(), false);
AudioInputStream decodedAudioIn = AudioSystem.getAudioInputStream(decodedFormat, audioIn);
format = decodedFormat;
audioIn = decodedAudioIn;
} else if (encoding.startsWith("GSM")) {
// Currently there's no way to decode GSM in WAV containers in Java.
// http://www.jsresources.org/faq_audio.html#gsm_in_wav
Log.warn(
"Failed to load audio file.\n" +
"Java cannot decode GSM in WAV containers; " +
"please re-encode this file to PCM format or remove it:\n" + ref
);
return null;
}
DataLine.Info info = new DataLine.Info(Clip.class, format);
if (AudioSystem.isLineSupported(info))
return new MultiClip(ref, audioIn);
// try to find closest matching line
Clip clip = AudioSystem.getClip();
AudioFormat[] formats = ((DataLine.Info) clip.getLineInfo()).getFormats();
int bestIndex = -1;
float bestScore = 0;
float sampleRate = format.getSampleRate();
if (sampleRate < 0)
sampleRate = clip.getFormat().getSampleRate();
float oldSampleRate = sampleRate;
while (true) {
for (int i = 0; i < formats.length; i++) {
AudioFormat curFormat = formats[i];
AudioFormat newFormat = new AudioFormat(
sampleRate, curFormat.getSampleSizeInBits(),
curFormat.getChannels(), true, curFormat.isBigEndian());
formats[i] = newFormat;
DataLine.Info newLine = new DataLine.Info(Clip.class, newFormat);
if (AudioSystem.isLineSupported(newLine) &&
AudioSystem.isConversionSupported(newFormat, format)) {
float score = 1
+ (newFormat.getSampleRate() == sampleRate ? 5 : 0)
+ (newFormat.getSampleSizeInBits() == format.getSampleSizeInBits() ? 5 : 0)
+ (newFormat.getChannels() == format.getChannels() ? 5 : 0)
+ (newFormat.isBigEndian() == format.isBigEndian() ? 1 : 0)
+ newFormat.getSampleRate() / 11025
+ newFormat.getChannels()
+ newFormat.getSampleSizeInBits() / 8;
if (score > bestScore) {
bestIndex = i;
bestScore = score;
}
}
}
if (bestIndex < 0) {
if (oldSampleRate < 44100) {
if (sampleRate > 44100)
break;
sampleRate *= 2;
} else {
if (sampleRate < 44100)
break;
sampleRate /= 2;
}
} else
break;
}
if (bestIndex >= 0)
return new MultiClip(ref, AudioSystem.getAudioInputStream(formats[bestIndex], audioIn));
// still couldn't find anything, try the default clip format
return new MultiClip(ref, AudioSystem.getAudioInputStream(clip.getFormat(), audioIn));
}
public SoundPlayer(String filePath) throws LineUnavailableException, UnsupportedAudioFileException, IOException {
File file = new File(filePath);
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
clip = AudioSystem.getClip();
clip.open(audioInputStream);
}