Engineering Practice: Developing a Batch Audio/Video Extraction Tool with AI Assistance
This article explores the engineering practices of developing a desktop tool for batch extracting audio from video files with the assistance of AI coding tools. It covers the entire workflow from requirement decomposition and technology selection to architecture design and core implementation details, providing a practical guide to building efficient, robust utility software.
I. Why a Batch Audio/Video Extraction Tool is Needed
Organizing course recordings, preparing podcast materials, or archiving meeting videos all share a common requirement: extracting audio from a batch of video files and outputting them in a unified, user-friendly format. Converting files manually is inefficient and prone to errors like missing or overwriting files. Encapsulating this repetitive task into a desktop application is a typical small-scale engineering project that covers UI design, file system operations, external program execution, concurrency, and error handling.
Intelligent AI coding assistants can significantly shorten the time from idea to prototype. However, the quality of the generated code depends on how clearly the requirements are described and whether the developer systematically validates the results. The following sections expand on this in the order of “requirements, tech selection, architecture, implementation, and validation.”
II. Requirement Breakdown: Turning Vague Requests into Acceptance Criteria
The more specific the requirements, the more stable the generated code will be. The requirements for a batch conversion tool can be broken down into four categories:
- Functional Requirements: Support common video formats as input; support exporting to mainstream audio formats like MP3 and WAV; support importing file lists and recursive directory scanning; support configuring input and output formats; support executing conversions and exiting the program.
- Interactive Requirements: Clear UI zones where the file list, format settings, and action buttons occupy distinct areas; display a progress bar and status bar during conversion.
- Stability Requirements: Must provide specific reasons when errors occur; the UI must not freeze during conversion; a single file failure must not affect the entire batch task.
- Engineering Requirements: Clear selection of programming language and UI library; clear code structure for easy future maintenance, packaging, and distribution.
The “UI must not freeze” requirement is the most easily overlooked. It is also the most common pitfall for beginners: if time-consuming operations are executed directly in the UI’s main thread, the window will become unresponsive during conversion.
Each requirement should be written in the format of “input, action, expected result.” For example: “Import a video file without an audio track; the program displays a prompt, skips the file, and continues converting the remaining files.” Such criteria can be used directly for acceptance testing, eliminating subjective judgment.
III. Technology Selection and Trade-offs
When selecting a tech stack, several dimensions must be compared: distribution cost, number of dependencies, performance, development complexity, and alignment with requirements.
UI Solutions
- Web wrapper solutions: High UI development efficiency, but introduces additional runtime environments and results in a large installation package. This is too heavy for a lightweight tool.
- Native desktop GUI libraries: Few dependencies, fast startup, suitable for lightweight tools. The trade-off is that the developer must manually handle threads and UI refreshes.
Audio/Video Processing Solutions
- Pure code implementation of decoding and encoding: High controllability, but covering a wide range of formats and handling codec details is complex, leading to high development and maintenance costs.
- Calling mature command-line audio/video processing tools: Comprehensive format support, mature and stable. The program only needs to concatenate parameters and parse results. The trade-off is that the tool must already be installed in the user’s environment, requiring a startup check.
Considering all factors, the approach chosen for this article is a “scripting language with a built-in GUI library, calling a command-line audio/video processing tool.” This combination has few dependencies, enables fast development, provides mature transcoding capabilities, and best fits the positioning of a utility tool.
IV. Overall Architecture: Separating UI, Tasks, and Execution
The code is divided into three layers based on responsibility:
- UI Layer: Responsible for displaying the file list, format settings, progress bar, and status bar, and converting user actions into events. The UI layer does not execute conversions directly.
- Task Layer: Responsible for converting the file list into a task queue, managing worker threads, aggregating progress, and deciding which errors need to be surfaced to the user.
- Execution Layer: Responsible for concatenating command parameters for each file, launching child processes, reading output, and returning success or failure results.
The benefit of this layering is that each layer can be tested independently. For instance, the execution layer can verify output correctness using sample files without a UI; the UI layer can verify progress bar and status bar display logic using simulated task results.
V. Core Implementation Details
5.1 Preventing UI Freezing
UI controls typically can only be updated in the main thread; time-consuming tasks must be placed in worker threads. After completing a step, the worker thread puts the result into a thread-safe queue, which is then retrieved and updated by the UI’s periodic callback in the main thread.
The following pseudocode illustrates the division of labor between threads and the UI:
# Pseudocode: illustrating the division of labor between threads and UIfunction on_start_clicked():tasks = build_task_list(selected_files, output_format)start_background_worker(tasks, progress_queue)ui.set_busy(true) # Disable the start button to prevent duplicate submissionsfunction worker_main(tasks, progress_queue):for index, task in enumerate(tasks):result = run_conversion(task) # Blocking call only occurs in the worker threadprogress_queue.put(("file_done", index, result))progress_queue.put(("all_done", null, null))function ui_poll(): # Executed periodically in the main thread by a UI timerwhile not progress_queue.empty():message = progress_queue.get()update_progress_bar_and_status(message)schedule_next_poll(100) # Check again after 100 milliseconds
This structure has three key points: time-consuming operations do not block the main thread; the worker thread does not directly modify UI controls; and the start button is disabled during task execution to avoid duplicate submissions.
5.2 Progress Bar and Status Bar
Progress calculation is divided into two levels. For a single file’s progress, you can first probe the video duration using a command, then read the time information output during conversion to calculate a percentage using “processed duration divided by total duration.” The overall progress of the batch task is calculated by file count:
Total Progress = (Completed Files + Current File Progress) / Total Files
The status bar displays the name of the file currently being processed, along with the number of completed and failed files. If the video duration cannot be obtained, it can fall back to a coarse-grained progress based on file count, noted in the status bar to avoid giving the user a false sense of precision.
5.3 Recursive Scanning and Format Filtering
When importing a directory, the program needs to traverse subdirectories and only retain supported video extensions. Note the following during implementation:
- Extension comparison should be case-insensitive;
.MP4and.mp4should be treated the same. - Maintain an extension whitelist rather than just excluding a few formats, making it easier to control the input scope.
- Be aware that symbolic links during traversal might create loops; record visited paths or do not follow links by default.
5.4 Preventing Output File Overwrites
In the same batch, files in different directories might share the same base name. If written directly, the latter result will overwrite the former. A common practice is to check the target path before writing; if it already exists, append an index:
# Pseudocode: auto-numbering for duplicate file namesfunction unique_path(path):if not exists(path):return pathbase, extension = split_extension(path)n = 1while exists(base + "_" + n + extension):n = n + 1return base + "_" + n + extension
This ensures old files are not silently overwritten. If the product requirements allow overwriting, an explicit option should be provided in the UI rather than defaulting to overwrite.
5.5 Environment Detection and Startup Prompts
Conversion relies on external command-line tools. If you wait until the first file fails to report an error, the user often sees a string of incomprehensible system error messages. A better approach is to check if the tool is executable at program startup or before clicking start. If not found, display a popup explaining what needs to be installed and how to check the path.
5.6 Error Classification and Prompts
The execution layer should read the child process’s return code and error output, categorizing the results into easily understandable classes, such as: file not found, format not supported, no audio track, insufficient permissions, insufficient disk space. The UI layer then provides specific prompts based on the category.
When a single file fails, the program should log the error, mark the file’s status, and continue processing subsequent files, rather than aborting the entire batch. After the batch finishes, the status bar or a result dialog should list the count and names of the failed files.
5.7 Exit and Resource Cleanup
If the user clicks exit during conversion, the program should first pop up a confirmation. Upon confirmation, set a cancel flag, terminate any running child processes, wait for the worker thread to finish, and then close the window.
To avoid leaving incomplete output files, it is recommended to write to a temporary file first, and only rename it to the final filename after successful conversion. This ensures that even if the process is canceled or power is lost, the output directory will not contain audio files that appear normal but are actually corrupted.
VI. Note on the Default Output Directory
During testing, a common question is “Is the default output directory the program’s installation directory after conversion?” There is no single answer to this; it should be chosen based on the use case and be user-modifiable.
- Defaulting output to the source file’s directory: This makes it easier for users to locate the results and is a relatively common practice.
