gpt4 book ai didi

android AudioRecord 类来录制音频并播放

转载 作者:行者123 更新时间:2023-11-29 20:49:10 25 4
gpt4 key购买 nike

我想录制音频并以 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
}

录制流和播放流是同时发生的吗?我该如何测试?

最佳答案

我想自己回答我的问题。

在上面的代码中,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");
}
}

关于android AudioRecord 类来录制音频并播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29626112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com