下面列出了怎么用javax.sound.sampled.AudioSystem的API类实例代码及写法,或者点击链接到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;
}
}
public static void main(String[] args) throws Exception {
// 1st checks Encoding.PCM_FLOAT is available
pcmFloatEnc = Encoding.PCM_FLOAT;
Encoding[] encodings = AudioSystem.getTargetEncodings(pcmFloatEnc);
out("conversion from PCM_FLOAT to " + encodings.length + " encodings:");
for (Encoding e: encodings) {
out(" - " + e);
}
if (encodings.length == 0) {
testFailed = true;
}
test(Encoding.PCM_SIGNED);
test(Encoding.PCM_UNSIGNED);
if (testFailed) {
throw new Exception("test failed");
}
out("test passed.");
}
public void play(File file, Clip clip) {
try {
// get a mixer and play clip like that
clip.addLineListener(new LineListener() {
@Override
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
clip.close();
}
}
});
clip.open(AudioSystem.getAudioInputStream(file));
clip.start();
} catch (Exception exc) {
exc.printStackTrace(System.out);
}
}
private boolean createSourceDataLine() {
if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip.createSourceDataLine()");
try {
DataLine.Info info = new DataLine.Info(SourceDataLine.class, loadedAudioFormat);
if (!(AudioSystem.isLineSupported(info)) ) {
if (DEBUG || Printer.err)Printer.err("Line not supported: "+loadedAudioFormat);
// fail silently
return false;
}
SourceDataLine source = (SourceDataLine) AudioSystem.getLine(info);
datapusher = new DataPusher(source, loadedAudioFormat, loadedAudio, loadedAudioByteLength);
} catch (Exception e) {
if (DEBUG || Printer.err)e.printStackTrace();
// fail silently
return false;
}
if (datapusher==null) {
// fail silently
return false;
}
if (DEBUG || Printer.debug)Printer.debug("Created SourceDataLine.");
return true;
}
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, OutputStream out) throws IOException {
//$$fb the following check must come first ! Otherwise
// the next frame length check may throw an IOException and
// interrupt iterating File Writers. (see bug 4351296)
// throws IllegalArgumentException if not supported
AiffFileFormat aiffFileFormat = (AiffFileFormat)getAudioFileFormat(fileType, stream);
// we must know the total data length to calculate the file length
if( stream.getFrameLength() == AudioSystem.NOT_SPECIFIED ) {
throw new IOException("stream length not specified");
}
int bytesWritten = writeAiffFile(stream, aiffFileFormat, out);
return bytesWritten;
}
@Override
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, OutputStream out) throws IOException {
Objects.requireNonNull(stream);
Objects.requireNonNull(fileType);
Objects.requireNonNull(out);
//$$fb the following check must come first ! Otherwise
// the next frame length check may throw an IOException and
// interrupt iterating File Writers. (see bug 4351296)
// throws IllegalArgumentException if not supported
AiffFileFormat aiffFileFormat = (AiffFileFormat)getAudioFileFormat(fileType, stream);
// we must know the total data length to calculate the file length
if( stream.getFrameLength() == AudioSystem.NOT_SPECIFIED ) {
throw new IOException("stream length not specified");
}
return writeAiffFile(stream, aiffFileFormat, out);
}
public VoicePlay() {
try {
format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100.0f, 16, 1, 2, 44100.0f, false);
DataLine.Info listenInfo = new DataLine.Info(TargetDataLine.class, format);
boolean l = AudioSystem.isLineSupported(listenInfo);
if (l) {
listenLine = (TargetDataLine) AudioSystem.getLine(listenInfo);
}
DataLine.Info playInfo = new DataLine.Info(SourceDataLine.class, format);
boolean p = AudioSystem.isLineSupported(listenInfo);
if (p) {
playLine = (SourceDataLine) AudioSystem.getLine(playInfo);
}
lineSupported = l && p;
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
/**
* WAVE�t�@�C�������[�h
* @param url WAVE�t�@�C����URL
*/
public static void load(URL url) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
// �I�[�f�B�I�X�g���[�����J��
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
// WAVE�t�@�C���̃t�H�[�}�b�g���擾
AudioFormat format = ais.getFormat();
// ���C�����擾
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format, AudioSystem.NOT_SPECIFIED);
// WAVE�f�[�^���擾
DataClip clip = new DataClip(ais);
// WAVE�f�[�^��o�^
clips[counter] = clip;
lines[counter] = (SourceDataLine)AudioSystem.getLine(info);
// ���C�����J��
lines[counter].open(format);
counter++;
}
private static void init() {
try {
// 44,100 Hz, 16-bit audio, mono, signed PCM, little endian
AudioFormat format = new AudioFormat((float) SAMPLE_RATE, BITS_PER_SAMPLE, MONO, SIGNED, LITTLE_ENDIAN);
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(format, SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE);
// the internal buffer is a fraction of the actual buffer size, this choice is arbitrary
// it gets divided because we can't expect the buffered data to line up exactly with when
// the sound card decides to push out its samples.
buffer = new byte[SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE/3];
}
catch (LineUnavailableException e) {
System.out.println(e.getMessage());
}
// no sound gets made before this call
line.start();
}
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, OutputStream out) throws IOException {
//$$fb the following check must come first ! Otherwise
// the next frame length check may throw an IOException and
// interrupt iterating File Writers. (see bug 4351296)
// throws IllegalArgumentException if not supported
WaveFileFormat waveFileFormat = (WaveFileFormat)getAudioFileFormat(fileType, stream);
//$$fb when we got this far, we are committed to write this file
// we must know the total data length to calculate the file length
if( stream.getFrameLength() == AudioSystem.NOT_SPECIFIED ) {
throw new IOException("stream length not specified");
}
int bytesWritten = writeWaveFile(stream, waveFileFormat, out);
return bytesWritten;
}
public void setGain(float ctrl) {
try {
Mixer.Info[] infos = AudioSystem.getMixerInfo();
for (Mixer.Info info : infos) {
Mixer mixer = AudioSystem.getMixer(info);
if (mixer.isLineSupported(Port.Info.SPEAKER)) {
try ( Port port = (Port) mixer.getLine(Port.Info.SPEAKER)) {
port.open();
if (port.isControlSupported(FloatControl.Type.VOLUME)) {
FloatControl volume = (FloatControl) port.getControl(FloatControl.Type.VOLUME);
volume.setValue(ctrl);
}
}
}
}
} catch (Exception e) {
}
}
public static void main(String[] args) throws Exception {
// 1st checks Encoding.PCM_FLOAT is available
pcmFloatEnc = Encoding.PCM_FLOAT;
Encoding[] encodings = AudioSystem.getTargetEncodings(pcmFloatEnc);
out("conversion from PCM_FLOAT to " + encodings.length + " encodings:");
for (Encoding e: encodings) {
out(" - " + e);
}
if (encodings.length == 0) {
testFailed = true;
}
test(Encoding.PCM_SIGNED);
test(Encoding.PCM_UNSIGNED);
if (testFailed) {
throw new Exception("test failed");
}
out("test passed.");
}
public static void main(String[] args) throws Exception {
Mixer.Info[] infos = AudioSystem.getMixerInfo();
log("" + infos.length + " mixers detected");
for (int i=0; i<infos.length; i++) {
Mixer mixer = AudioSystem.getMixer(infos[i]);
log("Mixer " + (i+1) + ": " + infos[i]);
try {
mixer.open();
for (Scenario scenario: scenarios) {
testSDL(mixer, scenario);
testTDL(mixer, scenario);
}
mixer.close();
} catch (LineUnavailableException ex) {
log("LineUnavailableException: " + ex);
}
}
if (failed == 0) {
log("PASSED (" + total + " tests)");
} else {
log("FAILED (" + failed + " of " + total + " tests)");
throw new Exception("Test FAILED");
}
}
public Soundbank getSoundbank(File file)
throws InvalidMidiDataException, IOException {
try {
AudioInputStream ais = AudioSystem.getAudioInputStream(file);
ais.close();
ModelByteBufferWavetable osc = new ModelByteBufferWavetable(
new ModelByteBuffer(file, 0, file.length()), -4800);
ModelPerformer performer = new ModelPerformer();
performer.getOscillators().add(osc);
SimpleSoundbank sbk = new SimpleSoundbank();
SimpleInstrument ins = new SimpleInstrument();
ins.add(performer);
sbk.addInstrument(ins);
return sbk;
} catch (UnsupportedAudioFileException e1) {
return null;
} catch (IOException e) {
return null;
}
}
public static void main(String[] args) throws Exception {
// 1st checks Encoding.PCM_FLOAT is available
pcmFloatEnc = Encoding.PCM_FLOAT;
Encoding[] encodings = AudioSystem.getTargetEncodings(pcmFloatEnc);
out("conversion from PCM_FLOAT to " + encodings.length + " encodings:");
for (Encoding e: encodings) {
out(" - " + e);
}
if (encodings.length == 0) {
testFailed = true;
}
test(Encoding.PCM_SIGNED);
test(Encoding.PCM_UNSIGNED);
if (testFailed) {
throw new Exception("test failed");
}
out("test passed.");
}
@Override
public void run() {
log("ConversionThread[" + num + "] started.");
try {
InputStream inStream = new ByteArrayInputStream(pcmBuffer);
AudioInputStream pcmStream = new AudioInputStream(
inStream, pcmFormat, AudioSystem.NOT_SPECIFIED);
AudioInputStream alawStream = AudioSystem.getAudioInputStream(alawFormat, pcmStream);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
int read = 0;
byte[] data = new byte[4096];
while((read = alawStream.read(data)) != -1) {
outStream.write(data, 0, read);
}
alawStream.close();
resultArray = outStream.toByteArray();
} catch (Exception ex) {
log("ConversionThread[" + num + "] exception:");
log(ex);
}
log("ConversionThread[" + num + "] completed.");
}
public static void main(String[] args) throws Exception {
Mixer.Info[] infos = AudioSystem.getMixerInfo();
log("" + infos.length + " mixers detected");
for (int i=0; i<infos.length; i++) {
Mixer mixer = AudioSystem.getMixer(infos[i]);
log("Mixer " + (i+1) + ": " + infos[i]);
try {
mixer.open();
for (Scenario scenario: scenarios) {
testSDL(mixer, scenario);
testTDL(mixer, scenario);
}
mixer.close();
} catch (LineUnavailableException ex) {
log("LineUnavailableException: " + ex);
}
}
if (failed == 0) {
log("PASSED (" + total + " tests)");
} else {
log("FAILED (" + failed + " of " + total + " tests)");
throw new Exception("Test FAILED");
}
}
public static void main(final String[] args) throws Exception {
// Prepare the audio file
File file = new File("audio.wav");
try {
AudioFormat format =
new AudioFormat(PCM_SIGNED, 44100, 8, 1, 1, 44100, false);
AudioSystem.write(getStream(format), Type.WAVE, file);
} catch (final Exception ignored) {
return; // the test is not applicable
}
try {
testSmallDelay(file);
testBigDelay(file);
} finally {
Files.delete(file.toPath());
}
}
public Soundbank getSoundbank(File file)
throws InvalidMidiDataException, IOException {
try {
AudioInputStream ais = AudioSystem.getAudioInputStream(file);
ais.close();
ModelByteBufferWavetable osc = new ModelByteBufferWavetable(
new ModelByteBuffer(file, 0, file.length()), -4800);
ModelPerformer performer = new ModelPerformer();
performer.getOscillators().add(osc);
SimpleSoundbank sbk = new SimpleSoundbank();
SimpleInstrument ins = new SimpleInstrument();
ins.add(performer);
sbk.addInstrument(ins);
return sbk;
} catch (UnsupportedAudioFileException e1) {
return null;
} catch (IOException e) {
return null;
}
}
private void loadClip() {
clipLoaded = true;
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(The5zigMod.getModDirectory(),
"media/" + The5zigMod.getDataManager().getUniqueId().toString() + "/" + ((ConversationChat) getMessage().getConversation()).getFriendUUID().toString() + "/" +
getAudioData().getHash()));
clip = (Clip) AudioSystem.getLine(new Line.Info(Clip.class));
clip.open(audioInputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
DirectAudioDevice(DirectAudioDeviceProvider.DirectAudioDeviceInfo portMixerInfo) {
// pass in Line.Info, mixer, controls
super(portMixerInfo, // Mixer.Info
null, // Control[]
null, // Line.Info[] sourceLineInfo
null); // Line.Info[] targetLineInfo
if (Printer.trace) Printer.trace(">> DirectAudioDevice: constructor");
// source lines
DirectDLI srcLineInfo = createDataLineInfo(true);
if (srcLineInfo != null) {
sourceLineInfo = new Line.Info[2];
// SourcedataLine
sourceLineInfo[0] = srcLineInfo;
// Clip
sourceLineInfo[1] = new DirectDLI(Clip.class, srcLineInfo.getFormats(),
srcLineInfo.getHardwareFormats(),
32, // arbitrary minimum buffer size
AudioSystem.NOT_SPECIFIED);
} else {
sourceLineInfo = new Line.Info[0];
}
// TargetDataLine
DataLine.Info dstLineInfo = createDataLineInfo(false);
if (dstLineInfo != null) {
targetLineInfo = new Line.Info[1];
targetLineInfo[0] = dstLineInfo;
} else {
targetLineInfo = new Line.Info[0];
}
if (Printer.trace) Printer.trace("<< DirectAudioDevice: constructor completed");
}
private boolean createClip() {
if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip.createClip()");
try {
DataLine.Info info = new DataLine.Info(Clip.class, loadedAudioFormat);
if (!(AudioSystem.isLineSupported(info)) ) {
if (DEBUG || Printer.err)Printer.err("Clip not supported: "+loadedAudioFormat);
// fail silently
return false;
}
Object line = AudioSystem.getLine(info);
if (!(line instanceof AutoClosingClip)) {
if (DEBUG || Printer.err)Printer.err("Clip is not auto closing!"+clip);
// fail -> will try with SourceDataLine
return false;
}
clip = (AutoClosingClip) line;
clip.setAutoClosing(true);
if (DEBUG || Printer.debug) clip.addLineListener(this);
} catch (Exception e) {
if (DEBUG || Printer.err)e.printStackTrace();
// fail silently
return false;
}
if (clip==null) {
// fail silently
return false;
}
if (DEBUG || Printer.debug)Printer.debug("Loaded clip.");
return true;
}
private boolean createClip() {
if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip.createClip()");
try {
DataLine.Info info = new DataLine.Info(Clip.class, loadedAudioFormat);
if (!(AudioSystem.isLineSupported(info)) ) {
if (DEBUG || Printer.err)Printer.err("Clip not supported: "+loadedAudioFormat);
// fail silently
return false;
}
Object line = AudioSystem.getLine(info);
if (!(line instanceof AutoClosingClip)) {
if (DEBUG || Printer.err)Printer.err("Clip is not auto closing!"+clip);
// fail -> will try with SourceDataLine
return false;
}
clip = (AutoClosingClip) line;
clip.setAutoClosing(true);
if (DEBUG || Printer.debug) clip.addLineListener(this);
} catch (Exception e) {
if (DEBUG || Printer.err)e.printStackTrace();
// fail silently
return false;
}
if (clip==null) {
// fail silently
return false;
}
if (DEBUG || Printer.debug)Printer.debug("Loaded clip.");
return true;
}
protected void printAllMixerNames() {
for(Mixer.Info info : AudioSystem.getMixerInfo()) {
P.out(info.getName(), " - ", info.getDescription());
Mixer m = AudioSystem.getMixer(info);
mixers.add(m);
UI.addButton(info.getName(), false);
}
}
public JavaSoundAudioClip(InputStream in) throws IOException {
if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip.<init>");
BufferedInputStream bis = new BufferedInputStream(in, STREAM_BUFFER_SIZE);
bis.mark(STREAM_BUFFER_SIZE);
boolean success = false;
try {
AudioInputStream as = AudioSystem.getAudioInputStream(bis);
// load the stream data into memory
success = loadAudioData(as);
if (success) {
success = false;
if (loadedAudioByteLength < CLIP_THRESHOLD) {
success = createClip();
}
if (!success) {
success = createSourceDataLine();
}
}
} catch (UnsupportedAudioFileException e) {
// not an audio file
try {
MidiFileFormat mff = MidiSystem.getMidiFileFormat(bis);
success = createSequencer(bis);
} catch (InvalidMidiDataException e1) {
success = false;
}
}
if (!success) {
throw new IOException("Unable to create AudioClip from input stream");
}
}
private boolean loadAudioData(AudioInputStream as) throws IOException, UnsupportedAudioFileException {
if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip->openAsClip()");
// first possibly convert this stream to PCM
as = Toolkit.getPCMConvertedAudioInputStream(as);
if (as == null) {
return false;
}
loadedAudioFormat = as.getFormat();
long frameLen = as.getFrameLength();
int frameSize = loadedAudioFormat.getFrameSize();
long byteLen = AudioSystem.NOT_SPECIFIED;
if (frameLen != AudioSystem.NOT_SPECIFIED
&& frameLen > 0
&& frameSize != AudioSystem.NOT_SPECIFIED
&& frameSize > 0) {
byteLen = frameLen * frameSize;
}
if (byteLen != AudioSystem.NOT_SPECIFIED) {
// if the stream length is known, it can be efficiently loaded into memory
readStream(as, byteLen);
} else {
// otherwise we use a ByteArrayOutputStream to load it into memory
readStream(as);
}
// if everything went fine, we have now the audio data in
// loadedAudio, and the byte length in loadedAudioByteLength
return true;
}
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {
// throws IllegalArgumentException if not supported
WaveFileFormat waveFileFormat = (WaveFileFormat)getAudioFileFormat(fileType, stream);
// first write the file without worrying about length fields
FileOutputStream fos = new FileOutputStream( out ); // throws IOException
BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
int bytesWritten = writeWaveFile(stream, waveFileFormat, bos );
bos.close();
// now, if length fields were not specified, calculate them,
// open as a random access file, write the appropriate fields,
// close again....
if( waveFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {
int dataLength=bytesWritten-waveFileFormat.getHeaderSize();
int riffLength=dataLength + waveFileFormat.getHeaderSize() - 8;
RandomAccessFile raf=new RandomAccessFile(out, "rw");
// skip RIFF magic
raf.skipBytes(4);
raf.writeInt(big2little( riffLength ));
// skip WAVE magic, fmt_ magic, fmt_ length, fmt_ chunk, data magic
raf.skipBytes(4+4+4+WaveFileFormat.getFmtChunkSize(waveFileFormat.getWaveType())+4);
raf.writeInt(big2little( dataLength ));
// that's all
raf.close();
}
return bytesWritten;
}
/**
* Load a FloatSample from a File object.
*/
@Override
public FloatSample loadFloatSample(File fileIn) throws IOException {
try {
return loadFloatSample(AudioSystem.getAudioInputStream(fileIn));
} catch (UnsupportedAudioFileException e) {
throw new IOException(e);
}
}
/**
* Creates a WaveData container from the specified inputstream
*
* @param is InputStream to read from
* @return WaveData containing data, or null if a failure occured
*/
public static WaveData create(InputStream is) {
try {
return create(
AudioSystem.getAudioInputStream(is));
} catch (Exception e) {
org.lwjgl.LWJGLUtil.log("Unable to create from inputstream");
e.printStackTrace();
return null;
}
}
static boolean test(Encoding enc) {
out("conversion " + enc + " -> PCM_FLOAT:");
Encoding[] encodings = AudioSystem.getTargetEncodings(enc);
for (Encoding e: encodings) {
if (e.equals(pcmFloatEnc)) {
out(" - OK");
return true;
}
}
out(" - FAILED (not supported)");
testFailed = true;
return false;
}