C#C#CSCore mp3文件中没有声音
使用CSCore库,我在名为C#C#CSCore mp3文件中没有声音,c#,.net,cscore,C#,.net,Cscore,使用CSCore库,我在名为BGM.cs的单独文件中编写了在类BGM中播放mp3文件的代码,播放方法是BGM.Play(“文件目录”),在表单中调用。但不知怎的,我无法从中得到任何声音。我已经检查了音量、编解码器和输出,我想不出还有什么可能导致这个问题 这是类文件的代码: public class BGM { public static void Play(string file) { using (IWaveSource soundSource = GetSou
BGM.cs
的单独文件中编写了在类BGM
中播放mp3文件的代码,播放方法是BGM.Play(“文件目录”)代码>,在表单中调用。但不知怎的,我无法从中得到任何声音。我已经检查了音量、编解码器和输出,我想不出还有什么可能导致这个问题
这是类文件的代码:
public class BGM
{
public static void Play(string file)
{
using (IWaveSource soundSource = GetSoundSource(file))
{
using (ISoundOut soundOut = GetSoundOut())
{
soundOut.Initialize(soundSource);
soundOut.Volume = 0.8f;
soundOut.Play();
}
}
}
private static ISoundOut GetSoundOut()
{
if (WasapiOut.IsSupportedOnCurrentPlatform)
return new WasapiOut();
else
return new DirectSoundOut();
}
private static IWaveSource GetSoundSource(string file)
{
return CodecFactory.Instance.GetCodec(file);
}
实际上,有几个原因可以解释为什么你的mp3不能播放
第一个原因是您尚未指定播放声音的设备。下面的代码获得了第一个可以呈现声音的设备,但是如果用户的计算机上连接了多个设备,那么这并不总是正确的。你必须妥善处理。必须在WasapiOut
对象上设置设备
第二个原因是在Play
方法中使用使用
语句。虽然清理实现了IDisposable
的对象总是一个好主意,但您不能总是立即这样做。在这种情况下,soundOut.Play()
不是阻塞方法,这意味着控件正在立即退出该方法,导致Dispose()
在soundOut
和soundSource
上被调用。这意味着声音将永远不会被播放(可能会启动一小段时间,但不足以真正听到)。基本上,您需要保留引用,并且仅在播放完成后才处理它们
请查看,了解如何实施完整的解决方案。我的代码应该让你开始
void Main()
{
using(var player = new BGM(@"D:\Test.mp3"))
{
player.Play();
// TODO: Need to wait here in order for playback to complete
// Otherwise, you need to hold onto the player reference and dispose of it later
Console.ReadLine();
}
}
public class BGM : IDisposable
{
private bool _isDisposed = false;
private ISoundOut _soundOut;
private IWaveSource _soundSource;
public BGM(string file)
{
_soundSource = CodecFactory.Instance.GetCodec(file);
_soundOut = GetSoundOut();
_soundOut.Initialize(_soundSource);
}
public void Play()
{
if(_soundOut != null)
{
_soundOut.Volume = 0.8f;
_soundOut.Play();
}
}
public void Stop()
{
if(_soundOut != null)
{
_soundOut.Stop();
}
}
private static ISoundOut GetSoundOut()
{
if (WasapiOut.IsSupportedOnCurrentPlatform)
{
return new WasapiOut
{
Device = GetDevice()
};
}
return new DirectSoundOut();
}
private static IWaveSource GetSoundSource(string file)
{
return CodecFactory.Instance.GetCodec(file);
}
public static MMDevice GetDevice()
{
using(var mmdeviceEnumerator = new MMDeviceEnumerator())
{
using(var mmdeviceCollection = mmdeviceEnumerator.EnumAudioEndpoints(DataFlow.Render, DeviceState.Active))
{
// This uses the first device, but that isn't what you necessarily want
return mmdeviceCollection.First();
}
}
}
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
if(_soundOut != null)
{
_soundOut.Dispose();
}
if(_soundSource != null)
{
_soundSource.Dispose();
}
}
_isDisposed = true;
}
}
public void Dispose()
{
Dispose(true);
}
}