I’m trying to get sound and graphic synchronization when playing music using a SourceDataLine - the Java code is a sound editor I wrote over 2 years ago and I’m updating it to be more useful since I failed to work this out 2 years ago and I’m now trying to get it to work
Although this isn’t a game, no doubt in a game you would want to be able to sychronize graphic events during a sound being played - so hopefully someone here knows the answer …
I have graphic views of each wave being played and want to run a bar across the graphics as it is playing
Other than synchronization, everything works fine.
The bar is drawn by a separate thread that loops doing: delete the old bar, get the position of the new bar, draw the new bar then sleep 100ms
I’ve tried:
- line.getFramePosition() or line.getMicrosecondPosition() but they appear to NOT be based on audio output, rather they seem to be the value of data written to the line
- process a full buffer first, call line.start() then get System.currentTimeMillis() then write each buffer - in the loop use currentTimeMillis() to get the current time offset from start of audio ouput - this produces two results - sometimes it’s very close to sync and other times it’s out (audio behind sync) by the same amount
- use a LineListener to catch START and get System.currentTimeMillis() as the time that audio output started - but in the START LineEvent the current frame is either around 500 (audio is behind by about 250ms) or around 4000 (sync almost correct) but for 44.1kHz - 250ms is approx 11000 frames so there is no obvious way to fix the time based on the frame position
As I said in 2) and 3) - the graphics is AHEAD of the audio - not lagging behind due to execution speed. I need to work out another way to do it properly or else work out how to calculate the sync offset in 2) or 3)
The audio is OK - no skips or jumps or drop outs (except on very rare occasions - and they are so rare that I don’t care about them)
I run the sound editor on 2 different machines:
- Athlon 1600+ 512MB using RedHat Linux 9 Java 1.4.2-b28
- PIII500 384MB WinXP Home Java 1.4.1_02
On the PIII500: sync is worse in all cases