我想录制音频并以WAV形式播放。我必须使用AudioRecord来完成它。有人可以帮我吗?
我经历了这个例子,
http://androidsourcecode.blogspot.com.au/2013/07/android-audio-demo-audiotrack.html
我无法理解通话模式和扬声器模式的作用。有人可以解释一下吗?
在该链接中使用此部分代码,
private void recordAndPlay() {
short[] lin = new short[1024];
int num = 0;
am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_IN_COMMUNICATION);
record.startRecording();
track.play();
while (true) {
num = record.read(lin, 0, 1024);
track.write(lin, 0, num);
}
}
num = record.read(lin, 0, 1024); is recording the audio.
track.play(); -- Plays the audio.
track.write(lin, 0, num); -- streams the audio
我不知道我是否理解正确,但我的理解是
record.startRecording(); -- Audio is recording
track.play(); -- playing the audio
while (true) {
num = record.read(lin, 0, 1024); -- Record gets stored
track.write(lin, 0, num); -- play the audio
}
录制流并播放流同时发生?我该怎么测试呢?
答案 0 :(得分:1)
我想自己回答我的问题。
在上面的代码中,recordAndPlay方法,同时记录和播放声音。
我拆分了代码。我录制了语音并将其存储到文件中,然后通过打开存储的文件并处理它来播放语音。
private void startRecording() {
final int CHANNELCONFIG = AudioFormat.CHANNEL_IN_MONO;
String filename = getTempFilename();
OutputStream os = null;
try {
os = new FileOutputStream(filename);
} catch(FileNotFoundException e) {
e.printStackTrace();
}
bufferSize = AudioRecord.getMinBufferSize(FREQUENCY,CHANNELCONFIG,AUDIO_FORMAT);
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,FREQUENCY,CHANNELCONFIG,AUDIO_FORMAT,bufferSize);
audioData = new byte[bufferSize];
audioRecord.startRecording();
int read = 0;
while (recording) {
read = audioRecord.read(audioData,0,bufferSize);
if(AudioRecord.ERROR_INVALID_OPERATION != read){
try {
os.write(audioData);
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
os.close();
} catch (IOException io) {
io.printStackTrace();
}
}
private void playRecording() {
String fileName = getFilename();
File file = new File(fileName);
byte[] audioData = null;
try {
InputStream inputStream = new FileInputStream(fileName);
int minBufferSize = AudioTrack.getMinBufferSize(44100,AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
audioData = new byte[minBufferSize];
AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,FREQUENCY,AudioFormat.CHANNEL_OUT_MONO,AUDI O_FORMAT,minBufferSize,AudioTrack.MODE_STREAM);
audioTrack.play();
int i=0;
while((i = inputStream.read(audioData)) != -1) {
audioTrack.write(audioData,0,i);
}
} catch(FileNotFoundException fe) {
Log.e(LOG_TAG,"File not found");
} catch(IOException io) {
Log.e(LOG_TAG,"IO Exception");
}
}