java播放声音 AudioStream.getData()异常
? 最近在写个小应用,用到了java用来播放声音的类库,网上有许多例子,于是就去找了一个。
?
?
code from http://dracularking.iteye.com/blog/738917?
?
import java.io.FileNotFoundException;import java.io.IOException;import java.net.URL;import sun.audio.AudioData;import sun.audio.AudioPlayer;import sun.audio.AudioStream;import sun.audio.ContinuousAudioDataStream;public class MusicPlay {private AudioStream as; // 单次播放声音用ContinuousAudioDataStream cas;// 循环播放声音// 构造函数public MusicPlay(URL url) {try {// 打开一个声音文件流作为输入as = new AudioStream(url.openStream());} catch(FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch(IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}// 一次播放 开始public void start() {if(as == null) {System.out.println("AudioStream object is not created!");return;} else {AudioPlayer.player.start(as);}}// 一次播放 停止public void stop() {if(as == null) {System.out.println("AudioStream object is not created!");return;} else {AudioPlayer.player.stop(as);}}// 循环播放 开始public void continuousStart() {// Create AudioData source.AudioData data = null;try {data = as.getData();} catch(IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}// Create ContinuousAudioDataStream.cas = new ContinuousAudioDataStream(data);// Play audio.AudioPlayer.player.start(cas);}// 循环播放 停止public void continuousStop() {if(cas != null) {AudioPlayer.player.stop(cas);}}}
?
不幸的是,在使用过程中,在使用循环播放时创建ContinuousAudioDataStream类时,?data = as.getData() 这一句出现了异常java.io.IOException: could not create AudioData object。
?
上网搜了好多资料都没有解决,有说音频文件格式不对,有说类库有问题,但是都没有解决,后来查看了AudioStream类源文件里的getData函数后发现,getData()对音频文件的长度是有限制的,不能超过1M, 终于找到原因了, nnd这种原因导致的异常真是悲剧,网上完全找不到这种情况,javaDoc里也没有说明。。。
?
http://www.docjar.com/html/api/sun/audio/AudioStream.java.html
102 public AudioData getData() throws IOException { 103 int length = getLength(); 104 105 //limit the memory to 1M, so too large au file won't load 106 if (length < 1024*1024) { 107 byte [] buffer = new byte[length]; 108 try { 109 ais.read(buffer, 0, length); 110 } catch (IOException ex) { 111 throw new IOException("Could not create AudioData Object"); 112 } 113 return new AudioData(format, buffer); 114 } 115 116 /* acis.setData(); 117 118 if (acis.stream instanceof ByteArrayInputStream) { 119 Format[] format = acis.getFormat(); 120 byte[] bytes = acis.getBytes(); 121 if (bytes == null) 122 throw new IOException("could not create AudioData object: no data received"); 123 return new AudioData((AudioFormat)format[0], bytes); 124 } 125 */ 126 127 throw new IOException("could not create AudioData object"); 128 }
?另外,播放声音的代码上面还是有问题的,应当参考一下的链接 http://www.java2s.com/Code/JavaAPI/sun.audio/newAudioStreamInputStreamarg0.htm
1 楼 雷博弈 2012-08-31 可否设置播放时间没?比如播放一分钟。 2 楼 asyty 2012-09-01 雷博弈 写道可否设置播放时间没?比如播放一分钟。这个么,其实你可以用一个计时线程控制的,播放音乐的API能不能设置时间参数我倒是没研究过