【问题标题】:C# mp3 file doesn't soundC# mp3 文件没有声音
【发布时间】:2016-06-14 20:10:20
【问题描述】:

大家好,提前感谢。

我正在尝试以网络形式播放 mp3 文件。我正在使用我在网上找到的这个类...

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);
    }
  }
}

...然后,我正在尝试使用这段代码从我的网络表单中播放...

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

...但它不起作用。拜托,谁能告诉我我做错了什么,它丢失了还是什么?。

顺便问一下,有没有更简单的方法来播放声音?我习惯在 Android 中做,大概也就五六行代码。

感谢您的时间和帮助。

【问题讨论】:

    标签: c# mp3 playback


    【解决方案1】:

    不幸的是,您使用的控件正在尝试在服务器上播放文件。您的目标是在客户端上播放它。为此,请向您的网页添加一个 html 5 音频控件(请参阅此link)。将音频文件放在某处,以便可以从您的网站下载。使用音频控件中的该路径将音频文件传送到用户的网络浏览器,以便他们可以播放它。

    <audio controls id='audioTagId'>
      <source src="path to media file.mp3' />
      <p>Your user agent does not support the HTML5 Audio element.</p>
    </audio>
    

    如果需要,您可以使用 javascript 根据操作触发控件。

    var v = document.getElementById("audioTagId");
    v.play();
    

    【讨论】:

      猜你喜欢
      • 2018-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多