public int readPcm(byte[] buffer, int offset, int length) throws IOException {
      synchronized (streamLock) {
         final int channels=identificationHeader.getChannels();

         if(lastAudioPacket==null) {
            lastAudioPacket=getNextAudioPacket();
         }
         if(currentPcm==null || currentPcmIndex>=currentPcmLimit) {
            AudioPacket ap=getNextAudioPacket();
            try {
               ap.getPcm(lastAudioPacket, currentPcm);
               currentPcmLimit=ap.getNumberOfSamples()*identificationHeader.getChannels()*2;
            }
            catch(ArrayIndexOutOfBoundsException e) {
               return 0;
            }
            currentPcmIndex=0;
            lastAudioPacket=ap;
         }
         int written=0;
         int i=0;
         int arrIx=0;
         for(i=currentPcmIndex; i<currentPcmLimit && arrIx<length; i++) {
            buffer[offset+arrIx++]=currentPcm[i];
            written++;
         }
         currentPcmIndex=i;
         return written;
      }
   }