使用声音文件发布 WPF/.NET 应用程序

问题描述 投票:0回答:1

我正在开发一个 WPF (.Net Core 6) 项目,我将其发布为 Self-ContainedSingle file,因此我得到了一个可运行的可执行文件 (.exe) 作为我发布的应用程序。 WPF 应用程序将在按键事件上播放声音(.wav 文件)。这适用于 VS2022 调试模式,因为声音文件位于文件夹

/Resources/SoundFile.wav
中的 .Net 项目中。

但是,由于声音文件的路径不正确,应用程序在运行已发布的可执行文件时崩溃。从 Self-ContainedSingle file 可执行文件运行时,如何配置声音文件的正确相对路径?

这就是代码现在的样子:

PlaySoundFile(GetSoundFilePath("../../../Resources/SoundFile.wav"));
        private void PlaySoundFile(string soundPath)
        {
                SoundPlayer activatedPlayer = new SoundPlayer(GetSoundFilePath(soundPath));
                activatedPlayer.Load();
                activatedPlayer.Play();
        }

        private string GetSoundFilePath(string soundPath)
        {
            Assembly? assembly = Assembly.GetEntryAssembly();
            string? baseDir = Path.GetDirectoryName(assembly.Location);
            return new DirectoryInfo(Path.Combine(baseDir, soundPath)).FullName;
        }

我试图在运行可执行文件时查找声音文件的路径,因为我相信它可能是在运行时创建的某个临时文件夹,并在 WPF 应用程序关闭后删除。但到目前为止还没有成功。

c# .net wpf audio core
1个回答
0
投票

考虑不传递路径,而是传递数据流,然后您可以将其加载到内存中并从那里进行流式传输,或者以流的形式获取资源。将其变成嵌入式资源。

© www.soinside.com 2019 - 2024. All rights reserved.