【问题标题】:How can I play a sound with defined start- and end-time in .Net如何在.Net中播放具有定义的开始和结束时间的声音
【发布时间】:2014-02-11 11:16:19
【问题描述】:

在我的 C# 项目中,我想播放具有指定开始和结束时间的声音。

我将System.Media.SoundPlayer.Play() 函数一起使用。但是使用这个功能,我只能播放整个声音文件,或者在计算运行时间后中止它。

实际上我想说的是,给定的声音文件应该例如在时间 1m:25s:30ms 开始,并且应该在时间 1m:50s:00ms 或在 10s 左右的持续时间之后结束。

有人知道他的问题的简单解决方案吗?

感谢 4 位帮助。

【问题讨论】:

  • 好的,这就是我上面写的,我可以做到。但是我怎么能说声音不应该在开始时开始,而是在开始后几秒钟?

标签: c# media-player audio duration


【解决方案1】:

不是一个真正的答案,但这个问题让我想知道你是否可以这样做:

long startPositionInBytes = 512;
long endPositionInBytes = 2048;

using ( var audioStream = File.OpenRead(@"audio.wav") )
{
    audioStream.Position = startPositionInBytes;

    using ( var player = new SoundPlayer(audioStream) )
    {
        player.Play();

        do
        {
            Thread.Sleep(1);
        } while ( audioStream.Position <= endPositionInBytes );

        player.Stop();
    }
}

【讨论】:

  • 可以工作。但是你知道我如何估计时间的字节位置吗?它们受采样率和压缩 a.s.o 的影响。 .
  • 并非没有编写可以解释波形格式的代码,此时您还不如自己实现音频播放。
【解决方案2】:

如果您想播放从特定时间开始并工作一段时间的后台媒体播放器(例如,音频文件),那么这段代码 sn-p 也很有用:

StorageFile mediaFile = await KnownFolders.VideosLibrary.GetFileAsync(fileName);//the path
BackgroundMediaPlayer.Current.SetFileSource(mediaFile);
BackgroundMediaPlayer.Current.Position = TimeSpan.FromMilliseconds(3000/*enter the start time here*/);
BackgroundMediaPlayer.Current.Play();
await Task.Delay(TimeSpan.FromMilliseconds(10000/*for how long you want to play*/));
BackgroundMediaPlayer.Shutdown();//stops the player

**但这仅适用于 Windows 8.1 及更高版本。 更多信息,请点击here...

【讨论】:

    【解决方案3】:

    最后我使用了 NAudio 库。这可以处理这个问题 - 不是以完美的方式,但可以。 见https://stackoverflow.com/a/13372540/2936206

    【讨论】:

      【解决方案4】:

      我通过在带有计时器控件和打开对话框的 C 语言程序中使用 Windows Media Player 来使其工作。 我遵循了一个使用表单上的按钮并使媒体播放器不可见的示例。 使用打开按钮打开文件后,使用打开对话框打开 mp3 文件,在播放按钮上,我输入了这段代码[最终效果是文件在位置 28.00 开始并在位置 32.50 结束]:

      private void button2_Click(object sender, EventArgs e)
      {
          axWindowsMediaPlayer1.URL = openFileDialog1.FileName;
          timer1.Start();
          axWindowsMediaPlayer1.Ctlcontrols.currentPosition = 28.00;
          axWindowsMediaPlayer1.Ctlcontrols.play();    
      }
      

      然后在计时器滴答事件中:

      private void timer1_Tick(object sender, EventArgs e)
      {
          if (axWindowsMediaPlayer1.Ctlcontrols.currentPosition >= 32.50)
          { axWindowsMediaPlayer1.Ctlcontrols.pause(); }
              label1.Text = String.Format("{0:0.00}", 
          axWindowsMediaPlayer1.Ctlcontrols.currentPosition);     
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-27
        • 1970-01-01
        • 1970-01-01
        • 2018-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多