我对使用NAudio有点陌生,所以我肯定缺少一些重要的东西,因此就是这个问题。
从示例/演示代码开始,我整理了一个尽可能简单的类来播放MP3或WAV文件:
public class AudioPlayer : IDisposable
{
WaveStream _waveStream; // sound data stream
WaveChannel32 _waveChannel32; // sound channel ??
IWavePlayer _iWavePlayer; // sound output driver
public bool IsPlaying
{
get { return _iWavePlayer != null
&& _iWavePlayer.PlaybackState
!= Wave.PlaybackState.Stopped; }
}
public PlaybackState PlaybackState
{
get { return _iWavePlayer.PlaybackState; }
}
public void LoadMp3(byte[] mp3Bytes)
{
Load(CreateInputStreamFromMp3Bytes(mp3Bytes));
}
public void LoadFile(string filename)
{
Load(CreateInputStream(filename));
}
void Load(WaveStream waveStream)
{
if (_iWavePlayer != null)
Dispose();
_iWavePlayer = new WaveOut();
_iWavePlayer.PlaybackStopped +=
new EventHandler(_iWavePlayer_PlaybackStopped);
_waveStream = waveStream;
_waveChannel32 = new WaveChannel32(_waveStream);
_waveChannel32.PadWithZeroes = false;
_iWavePlayer.Init(_waveChannel32);
}
void _iWavePlayer_PlaybackStopped(object sender, EventArgs e)
{
Stop();
}
static WaveStream CreateInputStreamFromMp3Bytes(byte[] mp3Bytes)
{
return new Mp3FileReader(new MemoryStream(mp3Bytes), false);
}
static WaveStream CreateInputStream(string fileName)
{
if (fileName.EndsWith(".wav"))
return new WaveFileReader(fileName);
else if (fileName.EndsWith(".mp3"))
return new Mp3FileReader(fileName);
else
throw new InvalidOperationException("Unsupported extension");
}
public void Play()
{
_iWavePlayer.Play();
}
public void Stop()
{
if (_iWavePlayer != null
&& _iWavePlayer.PlaybackState != PlaybackState.Stopped) {
_iWavePlayer.Stop();
_waveStream.Position = 0;
}
}
public void Dispose()
{
Stop();
if (_iWavePlayer != null) {
_iWavePlayer.Dispose();
_iWavePlayer = null;
}
if (_waveChannel32 != null) {
_waveChannel32.Dispose();
_waveChannel32 = null;
}
if (_waveStream != null) {
_waveStream.Dispose();
_waveStream = null;
}
}
}
我正在使用有问题的代码播放MP3文件(不是WAV)。
它在大多数情况下都可以正常工作,考虑到我将能够在项目中替换MediaElements,这非常棒。我遇到的问题是,一旦PlaybackStopped触发,
PlaybackState
会停留在Playing
上,而不是更改为Stopped
。为了解决这个问题,我订阅了PlaybackStopped
并从那里调用Stop()
。我必须这样调用
Stop()
是正常的吗?还是我在这里缺少什么? 最佳答案
看起来像个错误。如果您查看NAudio代码,WaveOut
不会更改PlaybackState
中的RaisePlaybackStoppedEvent
。但是DirectSoundOut
会将其更改为已停止。有点疯狂。