我想这样做:
Sistema.Util.MP3Player(@"sound1.mp3");
Sistema.Util.MP3Player(@"sound2.mp3");
namespace Sistema.Util.TextToSpeech
{
public class Player
{
static System.Windows.Media.MediaPlayer mp = new System.Windows.Media.MediaPlayer();
public static void MP3Player(string FileName, bool Async = false)
{
if (Async)
{
//mp.MediaOpened += new EventHandler(mp_MediaOpened);
//mp.MediaEnded += new EventHandler(mp_MediaEnded);
mp.Open(FileName.ToUri());
//mp.SpeedRatio = .2;
mp.Play();
}
else
{
// 03-06-2011
//using (var ms = System.IO.File.OpenRead(FileName)) // "test.mp3"
using (var rdr = new Mp3FileReader(FileName))
using (var wavStream = WaveFormatConversionStream.CreatePcmStream(rdr))
using (var baStream = new BlockAlignReductionStream(wavStream))
using (var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
{
//GC.KeepAlive(waveOut);
waveOut.Init(baStream);
waveOut.Play();
//waveOut.PlaybackStopped += new EventHandler(waveOut_PlaybackStopped);
while (waveOut.PlaybackState == PlaybackState.Playing)
{
System.Threading.Thread.Sleep(100);
}
}
}
}
}
}
问题是我有时会尝试,它会引发错误:
检测到 CallbackOnCollectedDelegate 消息:对类型为“NAudio!NAudio.Wave.WaveInterop+WaveCallback::Invoke”的垃圾收集委托进行了回调。这可能会导致应用程序崩溃、损坏和数据丢失。将委托传递给非托管代码时,托管应用程序必须使它们保持活动状态,直到保证它们永远不会被调用。
更新:我试过这个,但错误仍然发生在 3 次。您能否尝试阅读此代码:
void play(string FileName)
{
var mre = new System.Threading.ManualResetEvent(false); // created unsignaled
var callbackInfo = WaveCallbackInfo.FunctionCallback(); //lifetime outside using
using (var rdr = new Mp3FileReader(FileName))
using (var wavStream = WaveFormatConversionStream.CreatePcmStream(rdr))
using (var baStream = new BlockAlignReductionStream(wavStream))
using (var waveOut = new WaveOut(callbackInfo))
{
waveOut.Init(baStream);
waveOut.Play();
waveOut.PlaybackStopped += (sender, e) => { mre.Set(); };
mre.WaitOne();
}
}
play(@"C:\Users\Tony\AppData\Local\Temp\Sistema\Boa_Tarde(exclamacao).mp3");
play(@"C:\Users\Tony\AppData\Local\Temp\Sistema\Bem_vindo(exclamacao).mp3");
play(@"C:\Users\Tony\AppData\Local\Temp\Sistema\Boa_Tarde(exclamacao).mp3");
play(@"C:\Users\Tony\AppData\Local\Temp\Sistema\Bem_vindo(exclamacao).mp3");