You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中SoundPlayer无法找到WAV文件播放的问题求助

音符播放程序找不到WAV文件的问题解决

我写了个随机选择、显示并播放音符的程序,用随机数作为索引从数组里取音符名称和对应的WAV文件名,但一直报错提示“make sure the file is here”,可文件明明存在。试过把WAV文件放在项目文件夹的几乎所有子目录里都没用,不想在数组里写完整路径或者加路径拼接代码,请问问题出在哪?

我的代码

using System;
using System.Media;
class BassPractice {
  static void Main() {
    string[] notesArr = new string[]{"E - mi big","F - fa big","G - sol' big","A - la big",
                                   "H - si big","a - la small","h - si small","c - do small",
                                   "d - re small","e - mi small","f - fa small","g - sol' small","c1 - do first"};
    string[] locations = new string[]{"Ebig.wav","Fbig.wav","Gbig.wav","Abig.wav","Hbig.wav","a.wav","h.wav","c.wav","d.wav","e.wav","f.wav","g.wav","c1.wav"};
    Random note = new Random();
    SoundPlayer sound = new SoundPlayer();
    int ArrSize = notesArr.Length;
    int current = 0;
    Console.WriteLine ("Any Key to start");
    for (;;)
    {
        Console.ReadKey();
        Console.Clear();
        current = note.Next(ArrSize);
        Console.WriteLine ("note:");
        Console.WriteLine ("");
        Console.WriteLine (notesArr[current]);
        sound.SoundLocation = locations[current];
        sound.Play();
        Console.WriteLine ("");
        Console.WriteLine ("Any Key for the next one");
    }
  }
}

我原本以为存放.cs文件的文件夹是程序的根目录,把文件复制到那里没用,之后几乎试了所有位置还是不行。


问题原因与解决方法

  • 核心问题:程序运行的工作目录不是你的代码目录
    C#编译后的程序默认在输出目录运行(比如项目下的bin/Debug/net[版本号]或者bin/Release/net[版本号]),而不是你存放.cs源文件的目录。你之前把WAV文件放到代码目录,程序根本找不到。

  • 快速定位路径的方法
    在代码里加一行打印当前工作目录的代码,就能直接看到程序找文件的实际路径:

    // 需要先添加using System.IO;
    Console.WriteLine("当前工作目录:" + Directory.GetCurrentDirectory());
    

    运行程序后,把WAV文件复制到打印出来的路径里,就能正常播放了。

  • 更省心的规范做法
    如果用Visual Studio开发,直接设置WAV文件的属性,让它自动跟随编译输出:

    1. 在解决方案资源管理器里选中每个WAV文件
    2. 在右侧属性窗口里设置:
      • 复制到输出目录:选择「如果较新则复制」或「始终复制」
      • 生成操作:选择「内容」
        这样每次编译时,WAV文件会自动复制到程序运行的输出目录,不用手动复制,代码里的文件名也不用改。

内容的提问来源于stack exchange,提问作者Kaman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 15:42:02