WMPLib Console app exception on media play

0

I am not used to using InteropServices but what I am doing is using WMPLib to play songs from a console application. The application works as expected when I debug it from Visual Studio. But it crashes and gives me the following exception:

Unhandled Exception: System.Runtime.InteropServices.COMException: The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER))
   at WMPLib.IWMPPlayer4.get_controls()
   at ConsoleMP3Player.Program.Main(String[] args) in C:\Users\Ibrahim\Desktop\Console.Mp3\Console.Mp3\Program.cs:line 67

When I run it from command line:

C:\Users\Ibrahim\Desktop\Console.Mp3\Console.Mp3\bin\Debug>ConsoleMP3Player play

Following is the simple code for play command:

var _player = new WindowsMediaPlayer();
_player.URL = "Full path to a mp3 file";
_player.controls.play();

Any help is greatly appreciated.

c#
console-application
com-interop
wmplib
interopservices
asked on Stack Overflow Nov 7, 2015 by lbrahim

1 Answer

1

Instead of the bad COM control, try using the managed and thread-safe MediaPlayer class instead. Add a reference to PresentationCore and WindowsBase and try this:

using System.Windows.Media;

public void PlaySoundAsync(string filename)
{
    // This plays the file asynchronously and returns immediately.
    MediaPlayer mp = new MediaPlayer();
    mp.MediaEnded += new EventHandler(Mp_MediaEnded);
    mp.Open(new Uri(filename));
    mp.Play();
}

private void Mp_MediaEnded(object sender, EventArgs e)
{
    // Close the player once it finished playing. You could also set a flag here or raise another event.
    ((MediaPlayer)sender).Close();
}

User contributions licensed under CC BY-SA 3.0