0

我在提取存储在我的项目资源文件夹中的音频文件的文件目录时遇到问题。在我的项目中,我有一个 mysounds.resx 文件,我在其中添加了一个文件 (abc.mp3)。

            WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
            wplayer.URL = "E:/xyz.mp3";
            wplayer.settings.setMode("loop",false);
            wplayer.controls.play();

在这里,当我在 wplayer.URL 中给出“E:/xyz.mp3”目录时,它可以正常播放。但我想要做的是从存储 abc.mp3 的 mysounds.resx 文件中获取文件路径,并且我想使用 mysounds.resx 文件中的文件路径,而不是任何绝对路径。

有谁能帮助我吗?我的 C# 不是很好。我真的需要解决这个问题。先感谢您。

4

2 回答 2

1

将 Resource 中的音频文件写入临时文件,然后使用 WMPLib 播放。

//Set up the temp path, I'm using a GUID for the file name to avoid any conflicts
var temporaryFilePath = String.Format("{0}{1}{2}", System.IO.Path.GetTempPath(), Guid.NewGuid().ToString("N"), ".mp3") ;

//Your resource accessor, my resource is called AudioFile
using (var memoryStream = new MemoryStream(Properties.Resources.AudioFile))
using(var tempFileStream = new FileStream(temporaryFilePath, FileMode.Create, FileAccess.Write))
{
    //Set the memory stream position to 0
    memoryStream.Position = 0;

    //Reads the bytes from the audio file in resource, and writes them to the file
    memoryStream.WriteTo(tempFileStream);
}

//Play your file
WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
wplayer.URL = temporaryFilePath;
wplayer.settings.setMode("loop", false);
wplayer.controls.play();

//Delete the file after use
if(File.Exists(temporaryFilePath))
    File.Delete(temporaryFilePath);
于 2014-02-04T19:27:37.430 回答
0

a) 好的,首先将音频文件 (.wav) 添加到项目资源中。

  1. 从菜单工具栏(“VIEW”)打开“解决方案资源管理器”,或者直接按 Ctrl+Alt+L。
  2. 单击“属性”的下拉列表。
  3. 然后选择“Resource.resx”并按回车键。

打开项目资源

  1. 现在从组合框列表中选择“音频”。

将音频文件添加到资源

  1. 然后点击“添加资源”,选择音频文件(.wav)并点击“打开”。

浏览音频文件

  1. 选择音频文件并将“Persistence”属性更改为“Embedded in .resx”。

将音频文件嵌入资源

b) 现在,只需编写此代码即可播放音频。

在这段代码中,我在表单加载事件中播放音频。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Media; // at first you've to import this package to access SoundPlayer

namespace WindowsFormsApplication1
{
    public partial class login : Form
    {
        public login()
        {
            InitializeComponent();
        }

        private void login_Load(object sender, EventArgs e)
        {
            playaudio(); // calling the function
        }

        private void playaudio() // defining the function
        {
            SoundPlayer audio = new SoundPlayer(WindowsFormsApplication1.Properties.Resources.Connect); // here WindowsFormsApplication1 is the namespace and Connect is the audio file name
            audio.Play();
        }
    }
}

那它。
全部完成,现在运行项目(按 f5)并享受您的声音。
万事如意,再见。:)

于 2015-02-17T11:19:11.900 回答