Engineering Practices for AI-Assisted Generation of a Desktop Batch Audio/Video Conversion Tool
This article explores the engineering practices for using AI to generate a desktop batch audio and video conversion tool. It covers requirement decomposition, preventing UI freezing through multi-threading, modular architecture, safely invoking external transcoders, output file management strategies, hierarchical error handling, and a staged verification process. These practices ensure the reliability of AI-assisted code while highlighting the developer's ongoing responsibility for review and quality assurance.
1. Why Use a Batch Audio/Video Conversion Tool to Evaluate Code Generation
Desktop tools may seem simple, but they actually involve four types of complex issues simultaneously: file system operations, external process invocation, GUI interaction, and exception handling. The gap between a program that can only perform a single conversion and one that runs stably during large batch tasks primarily lies in these four areas. Therefore, this type of requirement is well-suited as a sample to evaluate the quality of automated programming.
When evaluating, focus on three points: whether the generated result can run directly, whether it covers every constraint in the requirements, and whether it handles inevitable boundary cases not explicitly stated in the requirements.
2. Requirement Breakdown: Turning a Sentence into Acceptable Specs
Vague requirements lead to vague code. Breaking down requirements into verifiable items is the first step to ensuring delivery quality.
2.1 Functional Requirements
- Support common video container formats as input, with the ability to export mainstream audio formats such as MP3 and WAV.
- Provide a file import list, supporting both adding individual files and adding an entire directory with recursive media file detection.
- Provide input and output format settings so users clearly know the format of the conversion result.
- Provide complete operation entries, including executing conversion, clearing the list, and exiting the program.
2.2 Non-Functional Requirements
- The interface must remain responsive during conversion; buttons, menus, and window dragging should not fail.
- Provide a progress bar and a status bar to reflect the overall progress and the currently processed file, respectively.
- When errors occur, pop up understandable prompts and write specific causes to the log.
- If the runtime environment lacks key dependencies, provide clear installation or configuration instructions before conversion begins.
2.3 Acceptance Checklist
Every requirement should correspond to an observable result. For example, “interface does not freeze” can be translated into: “During the conversion of 100 files, the response time for dragging the window and clicking the cancel button does not exceed one second.” Such phrasing makes it easy for testers to directly determine a pass or fail.
3. Core Challenge: Keeping the UI Responsive During Conversion
GUI programs rely on an event loop to handle user operations and redraw the interface. If time-consuming transcoding operations are executed directly within this loop, the UI thread will be occupied, causing the window to become unresponsive during the entire conversion process. The system may flag it as “Not Responding.”
The solution is to put the transcoding task into a background worker thread, leaving the UI thread solely responsible for displaying status and receiving user input.
3.1 Thread Responsibilities
- UI Thread: Creates controls, responds to clicks, and periodically refreshes the progress bar and status bar.
- Worker Thread: Takes files from the task queue, calls the transcoding program, calculates progress, and reports results.
- Task Queue: Passes pending tasks between the two, ensuring task order is controllable.
3.2 Cross-Thread Communication
Most GUI frameworks require controls to be modified only by the UI thread. The worker thread should not update the interface directly; instead, it should put progress messages into a thread-safe message queue. The UI thread periodically reads the queue via a timer and then updates the controls uniformly. This approach avoids UI anomalies caused by concurrent access and allows the UI refresh rate to be controlled independently.
3.3 Cancellation and Exit
Cancel operations should not forcefully terminate the thread, as forced termination may leave half-written output files. The recommended practice is to set a cancel flag, which the worker thread checks before processing each file. If the user exits the program midway through conversion, set the flag first, wait for the current subprocess to finish or actively terminate it, and finally clean up any incomplete output files.
3.4 Pseudocode Example
UI Thread:User clicks "Start Conversion"Disable start buttonPut pending file list into task queueStart worker threadWorker Thread:Loop:If cancel flag is set: Exit loopTake a file from the task queue. If queue is empty, end.Check if target path exists. If it does, generate a new filename with an index.Call external transcoding program in the form of an argument list.If return code is non-zero: Log error info, continue to next file.Put current file result and overall progress into message queue.UI Thread (Executed periodically, e.g., every 100 milliseconds):Read all pending messages from message queue.Update progress bar, status bar, and result list.If worker thread has ended: Re-enable start button.
4. Module Division
Dividing the code into several modules by responsibility helps locate issues and facilitates the future replacement of transcoding implementations.
| Module | Main Responsibilities | Boundaries with Other Modules |
|---|---|---|
| UI Module | Window layout, control events, progress and status display | Interacts only with the Scheduler module via the task interface |
| Scheduler Module | Manages task queue, worker thread lifecycle, cancel signals | Does not directly manipulate UI controls |
| Transcode Adapter Module | Constructs transcoding arguments, calls external programs, parses return results | Hides specific command-line details from upper layers |
| File Manager Module | Recursively scans directories, checks extensions, generates output paths, handles duplicates | Does not depend on the UI |
| Log and Error Module | Uniformly logs errors, generates user-readable prompt text | Called by other modules |
5. Standards for Calling External Transcoders
Audio and video decoding and encoding usually rely on mature command-line transcoding tools. When the program invokes it through a subprocess, note the following points.
5.1 Dependency Detection
At program startup or before conversion begins, check whether the transcoding tool can be found in the system path, and try to obtain its version information. If detection fails, directly prompt the user to install it or specify the executable file path, rather than waiting to report an error only when the first file conversion fails.
5.2 Parameter Passing
Concatenating filenames into a single command string is a common source of errors. Spaces, quotes, Chinese characters, or special symbols in filenames can cause parsing errors. If the filename comes from user input, it may also introduce command injection risks. The correct approach is to call the subprocess using an argument list, where each parameter is passed as an independent element and handled directly by the system without shell parsing.
5.3 Format Mapping
Audio encoding parameters vary by format. It is recommended to maintain a mapping table of extensions and encoding parameters, for example:
Audio output mapping = {"mp3": Corresponding encoder and bitrate parameters,"wav": Corresponding uncompressed encoding parameters,}
If an unsupported format is encountered, explicitly prompt “This output format is not supported” rather than silently skipping it or generating an empty file.
5.4 Return Result Handling
The return code and standard error output of the subprocess are the basis for judging whether the conversion was successful. A return code of zero usually indicates success, while a non-zero code indicates failure. Upon failure, both the return code and a summary of the error output should be recorded to facilitate troubleshooting specific causes such as corrupted files, videos without audio tracks, or unsupported encoders.
6. Output File Naming and Directory Strategy
6.1 Duplicate Handling
If a file with the same name already exists in the target path, overwriting it directly will cause data loss. A common practice is to append an index to the filename, such as “filename_1.mp3”, incrementing the loop until an available name is found. This logic should be placed in the File Manager module and evaluated before execution.
6.2 Default Output Directory
The default location of the output directory is a design decision that requires a clear trade-off. There are three common approaches:
- Default to the program’s directory: Simple to implement and convenient for portable use. However, if the program is installed in a directory requiring administrator privileges to write to, the conversion will fail. Users may also easily forget where the results are stored.
- Default to the source file’s directory: Matches most users’ intuition, keeping results together with the source materials. However, when batch-imported files come from multiple directories, the output will be scattered and difficult to manage uniformly.
- Default to a dedicated subdirectory under the user’s documents directory, with modifications allowed: Ensures writability and centralizes the results. The trade-off is that an additional setting is required, and the current output directory must be displayed on the UI.
Considering both writability and manageability, the third option is the most robust. Regardless of which approach is adopted, the UI should clearly display the current output directory so users do not have to guess the location of the results.
7. Error Handling and User Prompts
Errors should be handled in layers based on their impact scope.
- File-level errors: A single file cannot be read or conversion fails. Record the reason, mark the file as failed, and continue processing subsequent files.
- Task-level errors: The transcoding tool is missing or the output directory is not writable. Stop the current task and provide clear steps for resolution.
- Program-level errors: Uncaught exceptions. Record the complete stack trace to a log file and pop up a general prompt informing the user of the log location.
Prompt text should include three elements: Object (which file or setting), Reason (what happened), and Suggestion (what the user can do). For example: “File A failed to convert because no audio track was detected. You can skip it or check the source file.” This type of prompt is much more useful than a generic “Conversion failed.”
8. Verification Process
After generating the code, verification should be conducted in stages rather than relying solely on “whether it starts up.”
- Static Check: Run syntax checks and basic static analysis to identify undefined variables, unused imports, and obvious type errors.
- Smoke Test: Start the program, add files, execute conversion, and exit the program to confirm the main workflow is fully functional.
- Boundary Cases: Cover scenarios such as executing conversion with an empty list; paths containing spaces, non-ASCII characters, or special symbols; target file already existing; corrupted video files; videos without audio tracks; read-only output directories; and clicking exit during conversion.
- Responsiveness Test: Batch import a large number of files, continuously operate the interface during conversion, and record the response time of buttons and windows.
- Log Review: Check whether every failed case has a corresponding log entry and whether the log content is sufficient to locate the cause.
9. Reviewing AI-Generated Code
AI-assisted code generation can significantly shorten the initial development time, but manual review is still required before delivery.
- Check against the acceptance checklist item by item, rather than just seeing if the code covers the main features.
- Check thread safety: Confirm that UI controls are only modified by the UI thread and that shared data has explicit access protection.
- Check resource release: Ensure that subprocesses, file handles, and threads are correctly cleaned up even on exception paths.
- Check for extra features: Generated code often includes features beyond the requirements. Each addition should be evaluated for actual usefulness to avoid introducing unnecessary complexity and maintenance costs.
- Check security boundaries: Ensure external program calls use argument lists and that path inputs are validated.
10. Conclusion
A batch audio and video conversion tool encompasses common challenges in desktop software development. Breaking requirements down into verifiable items, using background threads to ensure UI responsiveness, safely invoking external programs via argument lists, improving diagnosability with hierarchical error handling, and confirming delivery quality through staged verification are the critical paths to reliably deploying such tools. AI-assisted programming can accelerate implementation, but the acceptance criteria and review responsibilities still belong to the developer.
