2016-06-14 108 views
0

大家好,並提前致謝。C#mp3文件沒有聲音

我想播放一個網頁形式的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); 
    } 
    } 
} 

......然後,我嘗試使用這段代碼從我的web表單玩...

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中完成它,它只有五六行代碼。

謝謝你的時間和幫助。

回答

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