我正在尝试创建一个函数i
,它接受一个mp3文件作为base64编码的字符串并使用PlaySoud
播放它。
System.Media.SoundPlayer
我目前在第 static void Main(string[] args)
{
var audioBytes = File.ReadAllBytes(@"PATH-TO-FILE");
var base64String = Convert.ToBase64String(audioBytes);
PlaySoud(base64String);
}
static void PlaySoud(string base64String)
{
var audioBuffer = Convert.FromBase64String(base64String);
using (var ms = new MemoryStream(audioBuffer))
{
var player = new System.Media.SoundPlayer(ms);
player.Play();
}
}
行遇到一个异常,说明player.Play()
堆栈跟踪
The wave header is corrupt
关于此错误的大多数MSDN讨论都指向将流位置重置为
at System.Media.SoundPlayer.ValidateSoundData(Byte[] data)
at System.Media.SoundPlayer.LoadAndPlay(Int32 flags)
at System.Media.SoundPlayer.Play()
at POC.Program.PlaySoud(String base64String) in c:\Users\user\Documents\Visual Studio 2013\Projects\POC\POC\Program.cs:line 21
at POC.Program.Main(String[] args) in c:\Users\user\Documents\Visual Studio 2013\Projects\POC\POC\Program.cs:line 12
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
,但它没有帮助。
您能告诉我0
功能有什么问题吗?我编码或解码mp3文件的方式有问题吗?
答案 0 :(得分:2)
SoundPlayer
类只能播放.wav文件。 - MSDN
您可以在应用中使用WindowsMediaPlayer播放.mp3文件以及许多其他格式。只需添加正确的参考文献即可。 (Help):
WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
wplayer.URL = "My MP3 file.mp3";
wplayer.controls.play();
更新:如果您需要从流播放mp3,请参阅Play audio from a stream using C#。或者,您也可以创建一个临时文件并播放它。