comparison game/SoundManager.java @ 107:dd896bc7352b

Fix sound streaming code to cope with partial buffer reads.
author Matti Hamalainen <ccr@tnsp.org>
date Thu, 03 Mar 2011 22:29:38 +0200
parents e1d657e6c25b
children 3551b61b3c0b
comparison
equal deleted inserted replaced
106:41c6cca69d60 107:dd896bc7352b
243 } 243 }
244 244
245 245
246 // use a short, 100ms (1/10th sec) buffer for filters that 246 // use a short, 100ms (1/10th sec) buffer for filters that
247 // change in real-time 247 // change in real-time
248 int bufferSize = playbackFormat.getFrameSize() * Math.round(playbackFormat.getSampleRate() / 10); 248 int bufferSize = playbackFormat.getFrameSize() * Math.round(playbackFormat.getSampleRate() / 20);
249 249
250 // create, open, and start the line 250 // create, open, and start the line
251 SourceDataLine line; 251 SourceDataLine line;
252 DataLine.Info lineInfo = new DataLine.Info(SourceDataLine.class, playbackFormat); 252 DataLine.Info lineInfo = new DataLine.Info(SourceDataLine.class, playbackFormat);
253 253
308 public void run() 308 public void run()
309 { 309 {
310 // get line and buffer from ThreadLocals 310 // get line and buffer from ThreadLocals
311 SourceDataLine line = (SourceDataLine) localLine.get(); 311 SourceDataLine line = (SourceDataLine) localLine.get();
312 byte[] buffer = (byte[])localBuffer.get(); 312 byte[] buffer = (byte[])localBuffer.get();
313 313
314 if (line == null || buffer == null) 314 if (line == null || buffer == null)
315 return; 315 return;
316
317 System.out.print("SMGR.SoundPlayer.run()\n");
318 316
319 // copy data to the line 317 // copy data to the line
320 try { 318 try {
321 int numBytesRead = 0; 319 boolean playing = true;
322 320 while (playing) {
323 while (numBytesRead != -1) {
324 // if paused, wait until unpaused 321 // if paused, wait until unpaused
325 synchronized (pausedLock) 322 synchronized (pausedLock)
326 { 323 {
327 if (paused) { 324 if (paused) {
328 try { 325 try {
333 } 330 }
334 } 331 }
335 } 332 }
336 333
337 // copy data 334 // copy data
338 numBytesRead = source.read(buffer, 0, buffer.length); 335 int bufPos = 0;
339 if (numBytesRead != -1) 336 while (bufPos < buffer.length && playing)
340 line.write(buffer, 0, numBytesRead); 337 {
338 int res = source.read(buffer, bufPos, buffer.length - bufPos);
339 if (res != -1)
340 bufPos += res;
341 else
342 playing = false;
343 }
344 if (playing)
345 line.write(buffer, 0, bufPos);
341 } 346 }
342 } 347 }
343 348
344 catch (IOException ex) { 349 catch (IOException ex) {
345 ex.printStackTrace(); 350 ex.printStackTrace();