JAVA按顺序播放多个wav音频
Posted 思微随想
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA按顺序播放多个wav音频相关的知识,希望对你有一定的参考价值。
用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(); } }
以上是关于JAVA按顺序播放多个wav音频的主要内容,如果未能解决你的问题,请参考以下文章
Java 脚本 - 当尝试按顺序一个接一个地播放音频时(通过 for 循环),一次播放所有音频