You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NAudio库在C#中控制音频播放速度时遇问题求解决

NAudio播放速度控制修复方案

以下是修正后的完整代码,可实现稳定的播放速度调整,避免异常:

using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using System.Windows.Forms;

namespace _2
{
    public partial class Form1 : Form
    {
        private WaveOutEvent outputDevice;
        private AudioFileReader audioFile;
        private VarispeedSampleProvider speedControl;

        public Form1()
        {
            InitializeComponent();
            // 初始化TrackBar范围,覆盖0.5x到2x常用变速区间
            trackBar1.Minimum = 5;
            trackBar1.Maximum = 20;
            trackBar1.Value = 10; // 默认1倍速播放
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "音频文件|*.mp3;*.wav;*.flac;*.ogg";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                // 切换新文件前先释放旧资源,避免冲突
                StopAndDisposeResources();
                txtFilePath.Text = openFileDialog.FileName;
            }
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtFilePath.Text))
                return;

            if (outputDevice == null)
            {
                outputDevice = new WaveOutEvent();
                outputDevice.PlaybackStopped += OnPlaybackStopped;
            }

            if (audioFile == null)
            {
                audioFile = new AudioFileReader(txtFilePath.Text);
                // 用VarispeedSampleProvider包装音频源,这是实现变速的核心步骤
                speedControl = new VarispeedSampleProvider(audioFile);
                // 同步TrackBar当前值作为初始速率
                speedControl.PlaybackRate = trackBar1.Value / 10f;
                outputDevice.Init(speedControl);
            }

            outputDevice.Play();
        }

        private void Button3_Click(object sender, EventArgs e)
        {
            outputDevice?.Stop();
        }

        private void TrackBar1_Scroll(object sender, EventArgs e)
        {
            if (speedControl != null)
            {
                // 强制限制速率范围,避免极端值导致音频失真或异常
                var rate = trackBar1.Value / 10f;
                speedControl.PlaybackRate = rate.Clamp(0.5f, 2f);
            }
        }

        private void OnPlaybackStopped(object sender, StoppedEventArgs args)
        {
            StopAndDisposeResources();
        }

        // 统一资源释放逻辑,避免重复代码和内存泄漏
        private void StopAndDisposeResources()
        {
            outputDevice?.Stop();
            outputDevice?.Dispose();
            outputDevice = null;

            speedControl = null;
            
            audioFile?.Dispose();
            audioFile = null;
        }

        // 窗体关闭时强制释放所有资源,防止残留音频进程
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            StopAndDisposeResources();
            base.OnFormClosing(e);
        }
    }
}

关键修改说明

  • 串联变速组件:原代码未实例化speedControl,必须将AudioFileReader包装进VarispeedSampleProvider后再传给WaveOutEvent,才能实现变速功能。
  • 完善资源管理:新增统一资源释放方法,覆盖播放停止、文件切换、窗体关闭等场景,彻底避免内存泄漏和资源占用异常。
  • 速率范围限制:通过代码和TrackBar属性双重限制速率在0.5x到2x之间,避免极端值导致的音频失真或程序崩溃。
  • 优化文件切换逻辑:选择新音频前自动清理旧资源,解决多音频加载冲突问题。
  • 默认速率初始化:窗体启动时设置TrackBar默认值为1倍速,确保首次播放状态正常。

内容的提问来源于stack exchange,提问作者Farbod Khosrozadeh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 11:05:31