infinity
infinity

Reputation: 1920

C# function to play base64 encoded mp3 file

I am trying to create a function PlaySoud that accepts a mp3 file as base64 encoded string and plays it using 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();
        }
    }

I am currently running into an exception on line player.Play() stating The wave header is corrupt with stack trace

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()

Most of the MSDN discussions on this error were pointing to resetting the stream position to 0, but it did not help.

Could you please let me know what is wrong with the PlaySound function? Is there an issue in the way I am encoding or decoding the mp3 file?

Upvotes: 1

Views: 3573

Answers (1)

Fᴀʀʜᴀɴ Aɴᴀᴍ
Fᴀʀʜᴀɴ Aɴᴀᴍ

Reputation: 6251

The SoundPlayer class can only play .wav files. - MSDN

You can use the WindowsMediaPlayer in your app to play .mp3 files as well as many other formats. Just add the correct references and you are good to go. (Help):

WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
wplayer.URL = "My MP3 file.mp3";
wplayer.controls.play();

Update: If you need to play your mp3 from a stream, see Play audio from a stream using C#. Alternatively you can also create a temporary file and play that.

Upvotes: 2

Related Questions