3
class Sound
{
private NAudio.Wave.BlockAlignReductionStream stream = null;
private NAudio.Wave.DirectSoundOut output = null;
private string fileName;
public Sound(string fileName)
{
this.fileName = fileName;
}
public void PlaySound()
{
if(fileName.EndsWith(".mp3"))
{
NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(fileName));
stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
}
else if (fileName.EndsWith(".wav"))
{
NAudio.Wave.WaveStream pcm = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(fileName));
stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
}
else throw new InvalidOperationException("Not a correct audio file type.");
output = new NAudio.Wave.DirectSoundOut();
output.Init(stream);
output.Play();
output.Volume = 0.5f;
}
public void Volume(float vol)
{
}
public void PausePlay()
{
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing) output.Pause();
else if (output.PlaybackState == NAudio.Wave.PlaybackState.Paused) output.Play();
}
}
public void Pause()
{
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing) output.Pause();
}
}
public void Play()
{
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Paused) output.Play();
}
}
public void DisposeWave()
{
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing) output.Stop();
output.Dispose();
output = null;
}
if (stream != null)
{
stream.Dispose();
stream = null;
}
}
public bool Over()
{
if (stream.Position == stream.Length)
return true;
return false;
}
public void Loop()
{
if (Over())
{
stream.Position = 0;
output.Play();
}
}
我真的不知道這裏有什麼問題,我很樂意提供幫助,我試圖改變輸出音頻的音量。 當我編譯此代碼時,我在output.volume = 0.5
中收到錯誤。錯誤是:NAudio音量變化
DirectSoundOut不支持設置音量,而是調整WaveProvider上的音量。
+1對於'新NAudio.Wave.WaveChannel32(新NAudio.Wave.WaveFileReader(fileName))'技巧,它幫助我在使用Mp3FileReader(不包含此屬性本身)時訪問'Volume'屬性。 – Sam