private void releaseResources() { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } finally { outputStream = null; } } if (tracks != null) { for (Track track : tracks) { try { track.release(); } catch (Exception e) { e.printStackTrace(); } } } }
@Override protected Exception doInBackground(Track... tracks) { Thread.currentThread().setPriority(Thread.MAX_PRIORITY - 1); try { this.tracks = tracks; for (Track track : tracks) { track.startStream(); if (sampleMode) { track.addOffsetFrame(-skipFrame); } } outputStream = new VorbisFileOutputStream(outputFileName); int read = 0; int totalRead = 0; int durationInMilli = (int) tracks[0].getDuration(); int durationInSec = durationInMilli / 1000; int estimateLength = durationInSec * PcmPlayer.SAMPLERATE * PcmPlayer.CHANNELS; int estimateLengthInPercent = estimateLength / 100; int preProgressInPercent = 0; int currentProgressInPercent = 0; short[] pcm = new short[BUFFER_SIZE]; int fadeInThreshold = pcm.length * FADE_IN_AND_OUT_DISCRETE_DIVIDER; int fadeOutThreshold = SAMPLE_LENGTH - pcm.length * FADE_IN_AND_OUT_DISCRETE_DIVIDER; float volume = 0; float volumeChangeAmount = 1f / FADE_IN_AND_OUT_DISCRETE_DIVIDER; while (!interrupted && read != -1) { Arrays.fill(pcm, (short) 0); for (Track track : tracks) { read = track.read(pcm); if (read == -1) { break; } } if (sampleMode) { if (totalRead > SAMPLE_LENGTH) { break; } if (totalRead < fadeInThreshold && volume < 1) { for (int i = 0; i < read; i++) { pcm[i] *= volume; } volume += volumeChangeAmount; } if (totalRead > fadeOutThreshold && volume > 0) { for (int i = 0; i < read; i++) { pcm[i] *= volume; } volume -= volumeChangeAmount; } } outputStream.write(pcm, 0, read); totalRead += read; currentProgressInPercent = Math.round(totalRead / estimateLengthInPercent); if (currentProgressInPercent > preProgressInPercent) { preProgressInPercent = currentProgressInPercent; publishProgress(currentProgressInPercent); } } return null; } catch (Exception e) { return e; } }