我在解压缩存储在项目资源文件夹中的音频文件的文件目录时遇到问题。在我的项目中,我有一个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#不太了解。我真的需要这个工作。提前谢谢。
答案 0 :(得分:0)
//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);
答案 1 :(得分:0)
a)好的,首先将音频文件(.wav)添加到项目资源中。
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)并享受你的声音
一切顺利,再见。 :)