1 Star 0 Fork 0

数心开物/QingSoundLib

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
LibObj.cs 3.01 KB
一键复制 编辑 原始数据 按行查看 历史
数心开物 提交于 2023-05-28 11:11 . init: 初始化仓库
using NAudio.Wave;
using Qing.Lang;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QingLib {
public class LibObj : Obj {
public LibObj() : base() {
Map["@播放音乐"] = new Expr(new PlaySound());
}
class PlaySound : Native {
public override string Name { get; set; } = "播放音乐";
public override string Desc { get; set; } = "参数1-字符串,可选参数2-逻辑,返回对象;打开参数1对应的音乐文件,默认立即播放,若传入参数2,并且为真,则不立即播放";
public override Expr Run(List<Expr> args, Ctx ctx, Obj? obj=null, List<Expr>? namedArgs=null) {
if (args.Count == 0) {
return Expr.Err("播放音乐函数需要文件路径参数");
}
if (args[0].Tp != TP.Str) {
return Expr.Err("播放音乐的文件路径参数必须是字符串类型");
}
string file = args[0].Str();
if (!file.StartsWith("/") && !file.Contains(":")) {
file = Directory.GetCurrentDirectory() + "/" + file;
}
if (!File.Exists(file)) {
return Expr.Err("要打开的音乐文件不存在");
}
bool wt = false;
if(args.Count > 1) {
wt = args[1].ToBool();
}
SoundDriver soundDriver = new SoundDriver();
Task.Run(async () => {
soundDriver.audioFile = new AudioFileReader(file);
using (var outputDevice = new WaveOutEvent()) {
soundDriver.Raw = outputDevice;
soundDriver.currFile = file;
outputDevice.Init(soundDriver.audioFile);
if (wt) {
outputDevice.Pause();
} else {
outputDevice.Play();
}
while (outputDevice.PlaybackState != PlaybackState.Stopped) {
await Task.Delay(500);
}
if (outputDevice.PlaybackState == PlaybackState.Stopped) {
try {
if (soundDriver.audioFile != null) {
soundDriver.audioFile.Close();
soundDriver.audioFile = null;
}
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
}
});
while (soundDriver.Raw is not WaveOutEvent) {
Thread.Sleep(20);
}
return new Expr(TP.Obj, soundDriver);
}
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/NjinN/qing-sound-lib.git
[email protected]:NjinN/qing-sound-lib.git
NjinN
qing-sound-lib
QingSoundLib
master

搜索帮助