|
|
根据你提供的测试代码,问题出现在 myAudioRecord.doRecord() 阻塞了测试线程,导致后续的 stopRecord() 无法执行。以下是改进建议:
问题分析
myAudioRecord.doRecord() 在主线程中执行,可能是阻塞式的调用
测试线程被阻塞后,无法继续执行后续的停止录音逻辑
需要将录音操作放到后台线程执行
改进方案
方案一:使用多线程执行录音
- @Test
- public void testRecordAndStop() {
- Log.d(tag, "testRecordAndStop");
- // 在新线程中执行录音
- Thread recordThread = new Thread(() -> {
- myAudioRecord.doRecord();
- });
- recordThread.start();
- try {
- // 等待一段时间让录音开始
- Thread.sleep(5000);
- Log.d(tag, "testRecordAndStop: stopping");
- // 停止录音
- myAudioRecord.isRecording = false;
- myAudioRecord.stopRecord();
-
- // 等待录音线程结束
- recordThread.join(3000); // 最多等待3秒
- } catch(Exception e){
- Log.e(tag, "Exception occurred: " + e.getMessage());
- }
- // 验证录音文件
- String testFilePath = myAudioRecord.filePath;
- Log.i(tag, "testRecordAndStop: filePath=" + testFilePath);
- assertTrue("File should exist and have content", new File(testFilePath).length() > 0);
- }
复制代码 方案二:优化 MyAudioRecord 类
建议修改 MyAudioRecord 类中的 doRecord() 方法,使其支持异步执行
- // 在 MyAudioRecord 类中添加异步录音方法
- public void startRecordAsync() {
- Thread recordThread = new Thread(() -> {
- doRecord();
- });
- recordThread.setDaemon(true); // 设置为守护线程
- recordThread.start();
- }
复制代码 然后在测试中使用:
- @Test
- public void testRecordAndStop() {
- Log.d(tag, "testRecordAndStop");
- // 异步开始录音
- myAudioRecord.startRecordAsync();
- try {
- Thread.sleep(5000); // 录音5秒
- Log.d(tag, "testRecordAndStop: stopping");
- myAudioRecord.isRecording = false;
- myAudioRecord.stopRecord();
- Thread.sleep(1000); // 给一些时间完成停止操作
- } catch(Exception e){
- Log.e(tag, "Exception occurred: " + e.getMessage());
- }
- String testFilePath = myAudioRecord.filePath;
- Log.i(tag, "testRecordAndStop: filePath=" + testFilePath);
- assertTrue("File should exist and have content", new File(testFilePath).length() > 0);
- }
复制代码 关键改进点
避免阻塞测试线程:将 doRecord() 放到单独线程执行
正确同步:使用 join() 或适当的等待机制确保线程协调
优雅停止:通过 isRecording 标志位控制录音循环
超时处理:添加合理的超时机制防止测试hang住
|
|