【发布时间】:2015-10-25 19:56:57
【问题描述】:
我正在尝试创建一个函数PlaySoud,它接受一个 mp3 文件作为 base64 编码字符串并使用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 并带有堆栈跟踪
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()
关于这个错误的大多数 MSDN 讨论都指向将流位置重置为 0,但这并没有帮助。
您能否告诉我PlaySound 函数有什么问题?我对 mp3 文件进行编码或解码的方式是否存在问题?
【问题讨论】:
-
您的代码没有立即出现问题 - 很可能是“波头已损坏” - 从某种意义上说,您播放的是非 WAV 文件(即 MP3)。如果您实际上尝试播放 MP3(根据您的帖子似乎是这种情况),那么您尝试使用
SoundPlayer而所有可以找到的文章 bing.com/search?q=c%23+play+mp3 都建议使用其他方式,这很奇怪。 -
编解码没问题。
SoundPlayer类只接受 .wav 文件 -
我的错!我确实在尝试使用
SoundPlayer播放*.mp3文件... :(
标签: c# audio base64 mp3 .net-4.5