package dcj.examples.Bandwidth;
import dcj.util.Bandwidth.*;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Source code from "Java Distributed Computing", by Jim Farley.
*
* Class: AudioProducer
* Example: 8-6
* Description: A producer of audio content.
* NOTE: This file contains incomplete example code only, which will
* not compile without additions and modifications.
*/
public abstract class AudioProducer extends ContentProducer
{
byte[] buffer = null;
long maxBuffer = 0;
long sampleRate;
// Buffer operations...
abstract protected void appendToBuffer(byte[] data);
abstract protected byte[] removeFromBuffer(long size);
// Method for computing new buffer size based on input
// data rate, our production rate, and the audio sample rate
abstract protected void resizeBuffer(float inRate, float outRate,
long audioRate);
// Method that decodes a given chunk of compressed data into
// audio samples.
abstract protected byte[] decode(byte[] cData);
public boolean produceAll() {
long bytesPerLoop = 512;
if (buffer == null) {
int maxLoop = 10;
for (int loop = 0; loop < maxLoop; loop++) {
byte[] data = produce(bytesPerLoop);
appendToBuffer(data);
}
// Assuming we know the rate that data is required by the
// AudioConsumer (i.e. the sample rate of the audio), then
// estimate the buffer size needed for continuous playback
resizeBuffer(source.getAverageRate(), monitor.getAverageRate(),
sampleRate);
}
boolean success = false;
if (dest != null) {
byte[] data = produce(bytesPerLoop);
while (data != null) {
success = dest.consume(data);
// Re-estimate buffer size
resizeBuffer(source.getLastRate(), monitor.getLastRate(),
sampleRate);
if (success)
data = produce(bytesPerLoop);
else
data = null;
}
}
return success;
}
protected byte[] doProduction(long limit) {
byte[] sData = null;
// Ask our source for compressed data, and decode it.
if (source != null) {
sData = source.produce(limit);
}
byte[] audioData = decode(sData);
// If our buffer is not full, add the new data to it
if (buffer.length < maxBuffer) {
appendToBuffer(audioData);
}
// If our buffer is now full, then return the requested
// amount of data, else return nothing.
if (buffer.length > maxBuffer) {
audioData = removeFromBuffer(limit);
}
else
audioData = null;
return audioData;
}
} |