How to play WAV audio file from Resources?

后端 未结 7 2115
面向向阳花
面向向阳花 2020-12-02 10:10

How can I play a WAV audio file in from my project\'s Resources? My project is a Windows Forms application in C#.

7条回答
  •  粉色の甜心
    2020-12-02 10:30

    There are two ways to do so as far as I know, list below:

    1. Use file path

    First put the file in the root folder of the project, then no matter you run the program under Debug or Release mode, the file can both be accessed for sure. Then use the class SoundPlayer to paly it.
    But in this way, if you want to release the project to users, you need to copy the sound files with its folder hierarchies except hierarchies the folder "Release" under the "bin" directory.

            var basePath = System.AppDomain.CurrentDomain.BaseDirectory;
            SoundPlayer player = new SoundPlayer();
            player.SoundLocation = Path.Combine(basePath, @"./../../Reminder.wav");
            player.Load();
            player.Play();
    
    1. Use resource

    Follow below animate, add "Exsiting file" to the project.

            SoundPlayer player = new SoundPlayer(Properties.Resources.Reminder);
            player.Play();
    

    The strength of this way is:
    Only the folder "Release" under the "bin" directory need to be copy when run the program.

提交回复
热议问题