用Java按顺序播放多个音频部件,不是同时播放。代码如下:
List<String> files = new ArrayList<String>(); files.add("barcode_prefix.wav"); for (char letter : barcode.toCharArray()) { files.add(letter + ".wav"); } files.add("barcode_suffix.wav"); byte[] buffer = new byte[4096]; for (String file : files) { try { AudioInputStream is = AudioSystem.getAudioInputStream(this.getClass().getResourceAsStream(file)); AudioFormat format = is.getFormat(); SourceDataLine line = AudioSystem.getSourceDataLine(format); line.open(format); line.start(); while (is.available() > 0) { int len = is.read(buffer); line.write(buffer, 0, len); } line.drain(); // **[DEIT]** wait for the buffer to empty before closing the line line.close(); } catch (Exception e) { e.printStackTrace(); } }
这个我在本地播放没有问题,放到服务器上会报错:
java.io.IOException: mark/reset not supported at java.util.zip.InflaterInputStream.reset(Unknown Source) at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(Unknown Source) at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source) at com.yulong.mes.winapp.form.quality.ForBatchOperationForm$PlayAudioRunnable.run(ForBatchOperationForm.java:4317) at java.lang.Thread.run(Unknown Source)
网上说要用BufferedInputStream封装一下。修改下代码确实如此:
List<String> files = new ArrayList<String>(); files.add("barcode_prefix.wav"); for (char letter : barcode.toCharArray()) { files.add(letter + ".wav"); } files.add("barcode_suffix.wav"); byte[] buffer = new byte[4096]; for (String file : files) { try { InputStream stream = this.getClass().getResourceAsStream(file); InputStream bufferedIn = new BufferedInputStream(stream); AudioInputStream is = AudioSystem.getAudioInputStream(bufferedIn); AudioFormat format = is.getFormat(); SourceDataLine line = AudioSystem.getSourceDataLine(format); line.open(format); line.start(); while (is.available() > 0) { int len = is.read(buffer); line.write(buffer, 0, len); } line.drain(); // **[DEIT]** wait for the buffer to empty before closing the line line.close(); } catch (Exception e) { e.printStackTrace(); } }