Reputation: 653
Hello everybody and thanks in advance.
I'm trying to play an mp3 file in a web form. I'm using this class that I've found in the web...
using System.Runtime.InteropServices;
using System.Text;
namespace MP3_Player
{
class MusicPlayer :System.IDisposable
{
public bool Repeat { get; set; }
public MusicPlayer(string filename)
{
const string FORMAT = @"open ""{0}"" type mpegvideo alias MediaFile";
string command = System.String.Format(FORMAT, filename);
mciSendString(command, null, 0, 0);
}
[DllImport("winmm.dll")]
private static extern long mciSendString(string lpstrCommand, StringBuilder lpstrReturnString, int uReturnLength, int hwndCallback);
public void open(string file)
{
string command = "open \"" + file + "\" type MPEGVideo alias MediaFile";
mciSendString(command, null, 0, 0);
}
public void play()
{
string command = "play MediaFile";
if(Repeat) command += " REPEAT";
mciSendString(command, null, 0, 0);
}
public void stop()
{
string command = "stop MediaFile";
mciSendString(command, null, 0, 0);
Dispose();
}
public void Dispose()
{
string command = "close MediaFile";
mciSendString(command, null, 0, 0);
}
}
}
...and then, I'm trying to play from my web form using this piece of code...
private MusicPlayer player;
...
private void Detalles_Click(object sender, EventArgs e)
{
...
Thread thread = new Thread(Musica);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
}
private void Musica()
{
if(player != null)
{
player.stop();
}
player = new MusicPlayer("~/Mantenimiento/MP3/ejemplo.mp3");
player.play();
}
... but it doesn't work. Please, can someone tell me what I'm doing wrong, it's missing or whatever?.
By the way, is there an easier way to play a sound? I'm used to do it in Android and it's just about five or six lines of code.
Thank you for your time and help.
Upvotes: 0
Views: 163
Reputation: 1045
Unfortunately the control you are using is attempting to play the file on the server. Your goal is to play it on the client. To do this, Add an html 5 audio control to your webpage (see this link). Place the audio file somewhere so that it can be downloaded from your website. Use that path in the audio control to deliver the audio file to the users web browser so they can then play it.
<audio controls id='audioTagId'>
<source src="path to media file.mp3' />
<p>Your user agent does not support the HTML5 Audio element.</p>
</audio>
You can use javascript to trigger the control if desired based on an action.
var v = document.getElementById("audioTagId");
v.play();
Upvotes: 1