Batch Audio/Video Converter for Desktop: Non-Blocking Architecture and Engineering Implementation
This article explains how to design and implement a desktop batch audio/video conversion tool that remains responsive during long-running work. It covers requirement decomposition, a four-layer architecture, batch file input and deduplication, output format parameter mapping, worker-thread and event-queue design, cancellation, progress and status reporting, error classification, external component detection, output directory and filename collision handling, testing and acceptance, and review criteria for AI-generated GUI code. The focus is on engineering practices that make the tool observable, recoverable, and usable under real batch workloads.
1. Requirements Breakdown: From Runnable to Deliverable
A batch audio/video conversion tool looks simple, but it involves five practical areas: file management, parameter configuration, long-running computation, UI feedback, and exception handling. Before writing code, break the requirements into verifiable items; otherwise, it is difficult to judge whether the program is actually complete.
Functional requirements can be organized as follows:
- Input: support adding individual files and directories, with an option to recursively scan subdirectories; recognize common video container formats.
- Output: support exporting common audio formats such as MP3 and WAV, with the necessary parameter settings for each output format.
- Operations: provide complete entry points for import, start conversion, cancel, clear list, and exit.
- Feedback: provide an overall progress bar, per-file status, status bar information, and error prompts.
Non-functional requirements are equally important:
- Responsiveness: during conversion, the UI must remain draggable, resizable, and clickable, and button states must update promptly.
- Robustness: a single file failure must not interrupt the entire batch, and running tasks must be handled properly before the program exits.
- Maintainability: input validation, conversion logic, and UI code should be separated so that the conversion engine can be replaced or formats can be added later.
2. Overall Architecture Design
A four-layer structure is recommended:
- UI layer: responsible for control layout, event binding, and state display, with no time-consuming computation.
- Task management layer: maintains the conversion queue and records the state of each task (waiting, running, succeeded, failed, canceled).
- Execution layer: calls the external conversion component in a worker thread, parses its output, and reports progress back.
- Environment adaptation layer: detects whether the external component is available and centralizes command generation and path handling.
The layers communicate through explicit messages. The UI layer sends “start” and “cancel” commands, while the execution layer sends back “progress”, “completed”, and “failed” events. This one-way event flow makes state changes easy to trace and simplifies troubleshooting.
Illustrative structure:
UI layer --commands--> Task management layer --tasks--> Worker thread --calls--> External converter^ |+--------------- event queue (progress/result/error) <---------------+
3. File List and Batch Input
The file list is the part users interact with most directly. The design needs to handle the following issues.
3.1 Extension Filtering
Use a whitelist rather than a blacklist. Video and audio extensions should be converted to lowercase before comparison to avoid missed matches caused by case differences. Keep the whitelist centralized in a configuration module so it can be extended later.
3.2 Recursive Scanning
When users add a directory, they usually expect subdirectories to be included at once. Recursive scanning requires attention to two points: first, when encountering a directory without permission, skip it and record the issue instead of failing the whole operation; second, set an access limit for symbolic links or record visited paths to prevent infinite traversal caused by circular references.
3.3 Deduplication
The same file may be added repeatedly. Deduplicate normalized absolute paths, unify path separators during comparison, and follow the case-sensitivity rules of the target operating system (some file systems are case-insensitive).
Illustrative pseudocode:
function add_files(paths, recursive):for p in paths:if is_directory(p):candidates = recursively_list_files(p) if recursive else list_direct_children(p)else:candidates = [p]for f in candidates:f = normalized_absolute_path(f)if extension(f).lower() not in whitelist:record_skip_reason(f)continueif f already in list:continuelist.append(new_task(f, status="waiting"))
4. Format Configuration and Parameter Mapping
The output format determines the conversion parameters. For common audio formats:
- WAV is an uncompressed or near-uncompressed PCM container. Files are large, making it suitable for scenarios that require further processing.
- MP3 is a lossy compression format and requires parameters such as bitrate. Higher bitrates usually mean better audio quality and larger files.
It is recommended to define a separate parameter set for each output format and show only the relevant options in the UI. For example, hide the bitrate option when WAV is selected so users do not mistakenly believe that the parameter takes effect.
The configuration must be validated before execution. Values such as sample rate and bitrate should fall within reasonable ranges; the output directory must exist and be writable; and the selected format combination must be supported by the external component. If validation fails, provide a clear prompt before conversion starts instead of exposing the problem only after a file fails.
5. Long-Running Tasks and UI Responsiveness
This is the key part of the entire tool. GUI frameworks typically use a single-threaded event loop to handle all UI operations. If conversion is executed directly inside an event handler, the UI can become unresponsive for minutes, appearing as a frozen window.
The correct approach is as follows:
- The main thread is responsible only for UI refresh and event dispatch.
- Conversion tasks are handed to worker threads, or the external program is run as a subprocess.
- Worker threads do not directly manipulate UI controls; all UI updates are sent back to the main thread through an event queue.
- The main thread periodically checks the queue through a timer and refreshes the UI.
Illustrative pseudocode:
worker(task_queue, event_queue, cancel_flag):while task = task_queue.get():if cancel_flag is set:mark remaining tasks as canceledbreakevent_queue.put(("start", task.id))process = start_external_conversion(task)for line in process.output:progress = parse_progress(line)event_queue.put(("progress", task.id, progress))result = wait_for_process_exit()event_queue.put(("completed" or "failed", task.id, result))ui_timer():while event = event_queue.get_nowait():update corresponding controlschedule_timer(100 ms)
Cancellation relies on the same flag. After the user clicks cancel, the worker thread stops assigning new tasks at the next checkpoint and terminates the current subprocess. The cancel operation must wait for the subprocess to actually exit; otherwise, a process may remain and hold file handles, preventing output files from being deleted.
When calling an external program, pass arguments as a list rather than concatenating them into a single string. This avoids incorrect parsing of spaces or special characters in paths and reduces the risk of command injection.
6. Progress Bar and Status Bar
Progress information has two levels: overall progress and per-file progress.
- Overall progress: calculated as completed tasks divided by total tasks, which is simple and reliable. For smoother progress, it can be weighted by the duration of each file.
- Per-file progress: many conversion components report the current time position in their output. Divide it by the total media duration to obtain a percentage. If the total duration cannot be obtained, show only a “processing” state rather than a false percentage.
The status bar should display three types of information: the current action (for example, “Converting file 3 of 12”), a summary of the most recent error, and the current output directory. Status bar content should be refreshed by events rather than redrawn frequently inside a loop.
7. Error Handling and User Prompts
Errors should be classified by nature, with different prompt methods for different categories:
| Category | Example | Handling |
|---|---|---|
| Missing environment | External converter not installed | Prompt at startup and disable the conversion button |
| Input issue | Corrupted file, no audio track | Mark the file as failed and continue with the next one |
| Output issue | Directory not writable, insufficient disk space | Validate before starting; if failure occurs during a run, stop the batch and prompt |
| Runtime exception | Process exits unexpectedly | Log the error, mark as failed, and optionally allow retry |
There are three handling principles: a single file failure must not affect the entire batch; environment errors should block operations as early as possible; and all errors should be written to logs with complete file paths and error output for reproduction.
Prompt methods should also differ. Fatal errors can use modal dialogs, while ordinary failures should only be highlighted in the list and reflected in the status bar to avoid frequent popups that interrupt the user.
8. External Component Detection
The tool depends on an external conversion component, so detection is needed at two points:
- At program startup: check whether the component is in the system search path, query version information, and confirm that it supports the required formats and encoders.
- Before conversion starts: confirm again that the component is executable, preventing the user from deleting or moving the file while the program is running.
Detection should provide an entry point for manually specifying the path. If automatic discovery fails, the user can choose the component location, and the program saves the path to a configuration file. When detection fails, the prompt should provide concrete installation or configuration steps rather than only saying “not found”.
9. Output Directory and Same-Name File Handling
Users often ask where converted files are saved by default. There are three common approaches:
- Program directory: simple to implement, but the program may be installed in a location that requires administrator permission to write, and output files will be mixed with program files.
- Source file directory: convenient for one-to-one mapping and suitable for single-run processing. During batch processing, however, output is scattered across multiple folders.
- User-specified unified directory: clear management and suitable for batch scenarios.
The recommended approach is to use the output directory last selected by the user by default; if none has ever been selected, use the source file directory and clearly display the current path in the UI. Using the program directory as the default output location is not recommended because it introduces permission and file management problems.
For same-name files, avoid direct overwriting. A common strategy is to append a number to the filename; for example, if “song.mp3” already exists, generate “song_1.mp3”. Two points require attention during implementation: increment the number until a nonexistent name is found, and create files in exclusive mode. Otherwise, two tasks running at the same time may generate the same name and overwrite each other.
10. Testing and Acceptance
A tool that runs correctly is not necessarily ready for delivery. At minimum, cover the following scenarios:
- Batch scale: convert dozens of files continuously and observe memory usage and UI responsiveness.
- Long-duration media: verify that progress calculation is correct and that the UI keeps refreshing.
- Abnormal input: corrupted files, videos without audio tracks, and files whose extensions do not match the actual format.
- Path issues: paths containing non-ASCII characters, spaces, and special symbols, as well as very long paths.
- Interruption operations: cancel during conversion, close the window directly, and delete source files during conversion.
- Output conflicts: same-name files, read-only directories, and insufficient disk space.
During acceptance, focus on whether the UI remains operable at all times. If the window becomes unresponsive while dragging it repeatedly or clicking buttons during conversion, the tool has not passed.
11. Acceptance of AI-Generated Code
Using AI tools to generate desktop programs is already a common development approach, but the generated results need the same review as human-written code. Successful compilation and program startup only show that there are no syntax-level problems. The review should focus on:
- Whether the threading model is correct and whether time-consuming operations block the UI thread.
- Whether exception paths are complete, such as subprocess failure, files being occupied, and directories not being writable.
- Whether path handling is safe and whether arguments are passed as lists.
- Whether functional claims match the actual implementation and whether there are buttons with only UI and no real logic.
It is advisable to turn the items above into a checklist and verify them one by one before delivery. For developers new to GUI programming, the most effective validation method is to repeatedly interact with the UI while a large file is being converted; this step usually exposes most threading problems.
Conclusion
The key to a usable batch conversion tool is to design the UI, task scheduling, external execution, and error handling separately. The main thread stays responsive, worker threads handle computation, and the event queue carries state. Together, these three parts meet the requirements of remaining responsive, observable, and recoverable. Details such as output directories, same-name files, and component detection may seem trivial, but they directly determine user experience. Acceptance should be based on real-world scenario testing rather than only on how complete the generated result appears.
