gpt4 book ai didi

android - AudioRecord - 写入 PCM 文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:48:05 28 4
gpt4 key购买 nike

我正在尝试使用 AudioRecord 类录制一些声音,然后将其写入输出 .pcm 文件。我希望我的程序继续录制,直到按下停止按钮。不幸的是,无论我录制多长时间,输出文件大小始终为 3528 字节,持续约 20 毫秒。同样根据 Toolsoft Audio Tools,该文件的属性是:44100Hz、16 位、立体声,即使我使用的是采样频率完全不同的单声道。

Thread recordingThread;
boolean isRecording = false;


int audioSource = AudioSource.MIC;
int sampleRateInHz = 44100;
int channelConfig = AudioFormat.CHANNEL_IN_MONO;
int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
int bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);

byte Data[] = new byte[bufferSizeInBytes];

AudioRecord audioRecorder = new AudioRecord(audioSource,
sampleRateInHz,
channelConfig,
audioFormat,
bufferSizeInBytes);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

public void startRecording(View arg0) {
audioRecorder.startRecording();
isRecording = true;
recordingThread = new Thread(new Runnable() {
public void run() {
String filepath = Environment.getExternalStorageDirectory().getPath();
FileOutputStream os = null;
try {
os = new FileOutputStream(filepath+"/record.pcm");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(isRecording) {
audioRecorder.read(Data, 0, Data.length);
try {
os.write(Data, 0, bufferSizeInBytes);
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
recordingThread.start();
}

public void stopRecording(View arg0) {
if (null != audioRecorder) {
isRecording = false;
audioRecorder.stop();
audioRecorder.release();
audioRecorder = null;
recordingThread = null;
}
}

我可以请你告诉我哪里出了问题吗?我希望答案不会是“一切”:)

最佳答案

try {
os.write(Data, 0, bufferSizeInBytes);
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}

这就是问题所在。您将在一次写入后关闭 FileOutputStream (os.close())。将其移出 while 循环:

while(isRecording) {
audioRecorder.read(Data, 0, Data.length);
try {
os.write(Data, 0, bufferSizeInBytes);
} catch (IOException e) {
e.printStackTrace();
}

}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}

关于android - AudioRecord - 写入 PCM 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13583827/

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