首页 > 解决方案 > 单击 Electron 应用程序中的按钮以在 VLC 中启动文件?

问题描述

我使用 Electron 和 Node 编写了一个小型媒体库管理器应用程序,主要作为学习框架的练习。该应用程序读取目录,将内容存储到本地 sqlite,然后在格式良好的数据表中显示数据。但是,我想知道是否可以添加功能,然后在 VLC 中打开这些文件。搜索实际上只会在 Electron 应用程序本身中找到播放媒体文件的信息,但我希望能够连续单击一个按钮以在 VLC 或等效媒体播放器中打开相应的文件。有没有办法做到这一点?

标签: node.jselectronvlc

解决方案


您实际上可以将 VLC 作为 Electron 应用程序的“子进程”启动。

假设您已将媒体文件的路径存储在名为 的变量中filepath,您可以像这样使用 NodeJS 的child_process模块:

var child_process = require ("child_process");

// Spawn VLC
var proc = child_process.spawn ("vlc", [ filepath ], { shell: true });

// Handle VLC error output (from the process' stderr stream)
proc.stderr.on ("data", (data) => {
    console.error ("VLC: " + data.toString ());
});

// Optionally, also handle VLC general output (from the process' stdout stream)
proc.stdout.on ("data", (data) => {
    console.log ("VLC: " + data.toString ());
});

// Finally, detect when VLC has exited
proc.on ("exit", (code, signal) => {
    // Every code > 0 indicates an error.
    console.log ("VLC exited with code " + code);
});

所有这些数据记录,通过proc.stderrproc.stdoutproc.on ("exit")是可选的,但是如果您只想允许您的应用程序一次生成一个 VLC 实例,您可以在生成第一个实例时设置一个全局变量,将其删除(或设置它为 false 或类似)并将整个块包装在 an 中,if () {}因此此代码一次只允许一个实例运行。

请注意,以这种方式生成的子进程实际上独立于您的应用程序;如果您的应用程序在 VLC 关闭之前退出,VLC 将继续运行。


推荐阅读