我希望将来自麦克风的write audio data
发送到文件。
我有2 threads
:一个"听"对于音频数据并将其发送到将其存储在队列中的第二个线程(消费者)。消费者线程不断轮询队列并在文件上将audioData写为byte []。
I use RandomAccessFile for the writing
。考虑到我的代码中的所有内容都是同步的,should I use some non-thread-safe class like FileChannel
?
下面是一些代码段:
读取音频数据
private void read(){
// fill the buffer with the mic input
readFully(buffer, 0, buffer.length);
// creates audioData from this buffer
WAVData audioData = new WAVData(buffer.length);
audioData.arrayCopy(buffer);
// add it to the consumer
mAudioWritter.add(audioData);
}
撰写音频数据 - 消费者分类
public void add(WAVEntity audioEntity){
mQueue.add(audioEntity);
synchronized (mLock) {
mLock.notify();
}
}
@Override
public void run() {
synchronized (mLock) {
while(!isFinalized){
//wait if queue is empty
while(mQueue.isEmpty()){
try {
mLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
WAVEntity entity = mQueue.poll();
if(entity != null){
try {
entity.writeOnFile(file);
} catch (AudioRecorderError e) {
// error handling
}
}
}
}
callback.threadFinished(this);
// try closing this file
try {
file.close();
} catch (IOException e) {
Log.e(getClass().getName(), e.getMessage(), e);
}
}
@Override
public boolean writeOnFile(RandomAccessFile fWriter) throws AudioRecorderError {
synchronized (data) {
//write on the file
try {
fWriter.write(data);
} catch (Exception e) {
AudioRecorderError error = new AudioRecorderError(e, "Data chunck was not written. See stack trace.");
throw error;
}
}
return false;
}