示例:WPF中Slider控件封装的缓冲播放进度条控件

2024-05-26 16:48

本文主要是介绍示例:WPF中Slider控件封装的缓冲播放进度条控件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、目的:模仿播放器播放进度条,支持缓冲任务功能

二、进度:

实现类似播放器中带缓存的播放样式(播放区域、缓冲区域、全部区域等样式)

实现设置播放中断时满足缓存够一定数量才继续播放的功能

实现设置缓存数量最大限制,即缓存够一定数量即停止缓存,减少开销

实现缓存中缓存进度的获取

 

二、示例(GIF)


 

三、实现:

1、UI部分

添加用户控件:BufferPlayControl.Xaml

设置Slider样式

   <!--Slider模板--><Style x:Key="Slider_RepeatButton" TargetType="RepeatButton"><Setter Property="Focusable" Value="false" /><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="RepeatButton"><Border Background="{TemplateBinding Foreground}" CornerRadius="5" /></ControlTemplate></Setter.Value></Setter></Style><Style x:Key="Slider_RepeatButton1" TargetType="RepeatButton"><Setter Property="Focusable" Value="false" /><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="RepeatButton"><Border Background="{TemplateBinding Background}" CornerRadius="5" /></ControlTemplate></Setter.Value></Setter></Style><Style x:Key="Slider_Thumb" TargetType="Thumb"><Setter Property="Focusable" Value="false" /><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Thumb"><Grid><Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition/></Grid.ColumnDefinitions><Border Background="{DynamicResource S_AccentBrush}"/><Border Grid.ColumnSpan="2" CornerRadius="4"  Background="{TemplateBinding Foreground}" Width="8" Height="8" Margin="-8"/></Grid></ControlTemplate></Setter.Value></Setter></Style><Style x:Key="Slider_CustomStyle" TargetType="Slider"><Setter Property="Focusable" Value="false" /><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Slider"><Grid><!--<Grid.Effect><DropShadowEffect BlurRadius="20" ShadowDepth="1" /></Grid.Effect>--><Border Grid.Column="1"  BorderBrush="Transparent" BorderThickness="1" CornerRadius="8,0,0,8"><Track Grid.Column="1" Name="PART_Track"><Track.DecreaseRepeatButton><RepeatButton Style="{StaticResource Slider_RepeatButton}" Foreground="{TemplateBinding Foreground}" Background="{TemplateBinding Background}"Command="Slider.DecreaseLarge"/></Track.DecreaseRepeatButton><Track.IncreaseRepeatButton><RepeatButton Style="{StaticResource Slider_RepeatButton1}" Foreground="{TemplateBinding Foreground}" Background="{TemplateBinding Background}"Command="Slider.IncreaseLarge"/></Track.IncreaseRepeatButton><Track.Thumb><Thumb Style="{StaticResource Slider_Thumb}" VerticalAlignment="Center"Foreground="{TemplateBinding Foreground}" Background="{TemplateBinding Background}"/></Track.Thumb></Track></Border></Grid></ControlTemplate></Setter.Value></Setter></Style><Style x:Key="Slider_CustomStyle1" TargetType="Slider"><Setter Property="Focusable" Value="false" /><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Slider"><Grid><!--<Grid.Effect><DropShadowEffect BlurRadius="20" ShadowDepth="1" /></Grid.Effect>--><Border Grid.Column="1"  BorderBrush="Transparent" BorderThickness="1" CornerRadius="8,0,0,8"><Track Grid.Column="1" Name="PART_Track"><Track.DecreaseRepeatButton><RepeatButton Style="{StaticResource Slider_RepeatButton}" Foreground="{TemplateBinding Foreground}" Background="{TemplateBinding Background}"Command="Slider.DecreaseLarge"/></Track.DecreaseRepeatButton><Track.IncreaseRepeatButton><RepeatButton Style="{StaticResource Slider_RepeatButton1}" Foreground="{TemplateBinding Foreground}" Background="{TemplateBinding Background}"Command="Slider.IncreaseLarge"/></Track.IncreaseRepeatButton><!--<Track.Thumb><Thumb Style="{StaticResource Slider_Thumb}"Foreground="{TemplateBinding Foreground}" Background="{TemplateBinding Background}"/></Track.Thumb>--></Track></Border></Grid></ControlTemplate></Setter.Value></Setter></Style>

用两个Slider叠加,一个用来播放进度,一个用来缓冲进度

   <Grid><Slider Height="5" Value="{Binding ElementName=control,Path=BufferValue,Mode=TwoWay}"  Maximum="{Binding ElementName=control,Path=MaxValue}" Minimum="{Binding ElementName=control,Path=MinValue}" SmallChange="{Binding ElementName=control,Path=SmallChange}"Background="{DynamicResource S_GrayNotice}" Foreground="Gray" Style="{StaticResource Slider_CustomStyle1}" VerticalAlignment="Center"IsHitTestVisible="False"/><Slider Height="5" Value="{Binding ElementName=control,Path=Value,Mode=TwoWay}" Maximum="{Binding ElementName=control,Path=MaxValue}" Minimum="{Binding ElementName=control,Path=MinValue}" SmallChange="{Binding ElementName=control,Path=SmallChange}"Background="Transparent" Foreground="{DynamicResource S_AccentBrush}" Style="{StaticResource Slider_CustomStyle}" VerticalAlignment="Center"/></Grid>

2、用户控件设置依赖属性

        /// <summary> 绑定最小值 </summary>public double MinValue{get { return (double)GetValue(MinValueProperty); }set { SetValue(MinValueProperty, value); }}// Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...public static readonly DependencyProperty MinValueProperty =DependencyProperty.Register("MinValue", typeof(double), typeof(BufferPlayControl), new PropertyMetadata(0.0, (d, e) =>{BufferPlayControl control = d as BufferPlayControl;if (control == null) return;//double config = e.NewValue as double;}));/// <summary> 绑定最大值 </summary>public double MaxValue{get { return (double)GetValue(MaxValueProperty); }set { SetValue(MaxValueProperty, value); }}// Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...public static readonly DependencyProperty MaxValueProperty =DependencyProperty.Register("MaxValue", typeof(double), typeof(BufferPlayControl), new PropertyMetadata(100.0, (d, e) =>{BufferPlayControl control = d as BufferPlayControl;if (control == null) return;//double config = e.NewValue as double;}));/// <summary> 绑定最小偏移量 </summary>public double SmallChange{get { return (double)GetValue(SmallChangeProperty); }set { SetValue(SmallChangeProperty, value); }}// Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...public static readonly DependencyProperty SmallChangeProperty =DependencyProperty.Register("SmallChange", typeof(double), typeof(BufferPlayControl), new PropertyMetadata(0.1, (d, e) =>{BufferPlayControl control = d as BufferPlayControl;if (control == null) return;//double config = e.NewValue as double;}));/// <summary> 设置当前播放值 </summary>public double Value{get { return (double)GetValue(ValueProperty); }set { SetValue(ValueProperty, value); }}// Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...public static readonly DependencyProperty ValueProperty =DependencyProperty.Register("Value", typeof(double), typeof(BufferPlayControl), new PropertyMetadata(30.0, (d, e) =>{BufferPlayControl control = d as BufferPlayControl;if (control == null) return;//double config = e.NewValue as double;}));/// <summary> 设置当前缓冲值 </summary>public double BufferValue{get { return (double)GetValue(BufferValueProperty); }set { SetValue(BufferValueProperty, value); }}// Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...public static readonly DependencyProperty BufferValueProperty =DependencyProperty.Register("BufferValue", typeof(double), typeof(BufferPlayControl), new PropertyMetadata(50.0, (d, e) =>{BufferPlayControl control = d as BufferPlayControl;if (control == null) return;//double config = e.NewValue as double;}));

3、测试代码

测试代码UI部分:开始、暂停、继续和显示进度、缓冲进度

            <GroupBox Header="缓冲播放进度条"><StackPanel><wpfcontrollib:BufferPlayControl x:Name="control_bufferPlay"/><TextBlock x:Name="txt_persent"/><TextBlock Text="{Binding ElementName=control_bufferPlay,Path=Value}"/><Button Content="开始" Click="Button_Click"/><Button x:Name="btn_play" Content="暂停" Click="Button_Click_1"/></StackPanel></GroupBox>

测试代码后台逻辑:

点击播放代码部分

            List<IBufferPlayEntity> bufferPlays = new List<IBufferPlayEntity>();//  Message:构造1000个测试数据for (int i = 0; i < 1000; i++){BufferPlayEntity entity = new BufferPlayEntity();bufferPlays.Add(entity);}//  Message:初始化控件this.control_bufferPlay.MinValue = 0;this.control_bufferPlay.Value = 0;this.control_bufferPlay.BufferValue = 0;this.control_bufferPlay.MaxValue = bufferPlays.Count;//  Message:开始缓冲引擎BufferPlayEngine bufferPlayEngine = new BufferPlayEngine(bufferPlays);bufferPlayEngine.RefreshCapacity(5);bufferPlayEngine.Start();Action<bool, int, int> action = (l, k, n) =>{Application.Current.Dispatcher.Invoke(() =>{if (l){this.txt_persent.Text = "缓冲完成..";}else{string p = (Convert.ToDouble(k) * 100 / Convert.ToDouble(n)).ToString();this.txt_persent.Text = "缓冲中.." + p + "%";}});};//  Message:刷新播放进度Task.Run(() =>{for (int i = 0; i < bufferPlays.Count; i++){//  Message:设置当前播放进度值Application.Current.Dispatcher.Invoke(() =>{this.control_bufferPlay.Value = i;});//  Message:检查当前是否已经暂停while (true){bool result = false;Application.Current.Dispatcher.Invoke(() =>{result = this.btn_play.Content.ToString() == "暂停";});if (result) break;Thread.Sleep(1000);}Thread.Sleep(100);//  Message:阻塞等待当前进度是否可以播放bufferPlayEngine.GetWaitCurrent(l => l == bufferPlays[i], action);}});//  Message:刷新下载进度Task.Run(() =>{while (true){Thread.Sleep(100);Application.Current.Dispatcher.Invoke(() =>{this.control_bufferPlay.BufferValue = bufferPlayEngine.GetBufferSize((int)this.control_bufferPlay.Value);});}});

点击暂停或继续代码部分:

            Button button = sender as Button;button.Content = button.Content.ToString() == "暂停" ? "继续" : "暂停";

测试任务实体:继承任务抽象类基类或接口,实现一个随机等待1-2秒完成的方法

public class BufferPlayEntity : BufferPlayEntityBase{public int IsLoaded { get; set; }Random random = new Random();public override void DoStart(){Thread.Sleep(random.Next(1, 2) * 1000);}}

 

4、核心缓冲引擎:

 

BufferPlayEngine:

设置可播放容量:在播放过程中,播放阻塞后需要缓冲的容量

设置播放缓冲总量:为了节省性能,当达到当前播放容量时,停止继续缓冲

设置并行任务数量:多线程执行任务的并行数量

原理:

Start()方法:后台创建多个缓冲线程去根据当前播放的任务去执行缓冲任务,获取第一个没有下载的任务,当任务超过最大缓冲容量时不执行下载

GetWaitCurrent()方法:如果当前任务已经完成则直接返回,如果当前任务未完成则需要等待可执行播放数量Capacity设置的数量都下载完成时才取消阻塞返回要执行的任务;

 

GetBufferSize()方法:获取当前已经缓冲好的数量,用于更新缓冲区域进度条

 

    /// <summary> 缓冲播放引擎 </summary>public class BufferPlayEngine{/// <summary> 可播放容器量 </summary>public int Capacity { get; set; } = 10;/// <summary> 总缓冲容器量 </summary>public int CapacityTotal { get; set; } = 10;/// <summary> 同时下载的任务数量 </summary>public int TaskCount { get; set; } = 5;//  Message:所有的文件列表List<IBufferPlayEntity> _entitys = new List<IBufferPlayEntity>();//  Message:当前播放的节点IBufferPlayEntity _current;public BufferPlayEngine(List<IBufferPlayEntity> entitys){_entitys = entitys;_current = entitys.First();}/// <summary> 刷新缓冲数量 </summary>public void RefreshCapacity(int count){//  Do:可播放队列设置15sthis.Capacity = count * 5;Do:后台缓存最多队列设置成5分钟this.CapacityTotal = count * 2 * 10;}CancellationTokenSource cts = new CancellationTokenSource();Semaphore _semaphore1 = new Semaphore(1, 1);/// <summary> 开始播放 </summary>public void Start(){if (cts != null){cts.Cancel();_semaphore1.WaitOne();}cts = new CancellationTokenSource();//  Message:启动当前位置的顺序下载任务Task.Run(() =>{//  Message:并行运行ParallelLoopResult result = Parallel.For(0, this.TaskCount, k =>{while (true){if (cts.IsCancellationRequested) break;int index = this._entitys.FindIndex(l => l == _current);var downs = _entitys.Skip(index).Take(this.CapacityTotal).Where(l => l.IsLoaded == 0);//  Message:超出最大下载缓存数量则等待if (downs == null || downs.Count() == 0){Thread.Sleep(1000);continue;}downs.FirstOrDefault()?.Start();}});_semaphore1.Release();}, cts.Token);}/// <summary> 停止引擎 </summary>public void Stop(){if (cts != null){cts.Cancel();}flag = false;}bool flag = true;Semaphore _semaphore = new Semaphore(1, 1);/// <summary> 获取下好的文件 返回null则需要等待 </summary>public IBufferPlayEntity GetWaitCurrent(Predicate<IBufferPlayEntity> match, Action<bool, int, int> action){var result = this._entitys.Find(match);int now = this._entitys.FindIndex(match);_current = result;if (result.IsLoaded == 2){return result;}else{//  Message:停止上一个获取任务flag = false;_semaphore.WaitOne();flag = true;var waitCache = _entitys.Skip(now).Take(this.Capacity).ToList();while (!waitCache.TrueForAll(l => l.IsLoaded == 2)){if (!flag){_semaphore.Release();return null;}Thread.Sleep(500);action(false, waitCache.FindAll(l => l.IsLoaded == 2).Count, waitCache.Count);}action(true, waitCache.FindAll(l => l.IsLoaded == 2).Count, waitCache.Count);_semaphore.Release();return result;}}/// <summary> 获取下好的文件 返回null则需要等待 </summary>public IBufferPlayEntity GetWaitCurrent(int index, Action<bool, int, int> action){var result = this._entitys[index];return this.GetWaitCurrent(l => l == result, action);}/// <summary> 获取当前缓存完的位置 </summary>public int GetBufferSize(Predicate<IBufferPlayEntity> match){int index = this._entitys.FindIndex(l => l == _current);return this.GetBufferSize(index);}/// <summary> 获取当前缓存完的位置 </summary>public int GetBufferSize(int index){var isdown = _entitys.Skip(index).LastOrDefault(l => l.IsLoaded == 2);if (isdown == null) return 0;return this._entitys.FindIndex(l => l == isdown);}/// <summary> 清理缓存数据 </summary>public void Clear(){}//  Message:是否是向前播放bool _isForward = true;/// <summary> 反向播放 </summary>public void RefreshPlayMode(bool forward){if (_isForward = forward) return;_isForward = forward;_entitys.Reverse();}}

缓冲引擎任务执行接口和抽象基类

IBufferPlayEntity:

    /// <summary> 缓冲任务接口 </summary>public interface IBufferPlayEntity{/// <summary> 是否执行完成 </summary>int IsLoaded{get;set;}/// <summary> 开始任务 </summary>void Start();}

BufferPlayEntityBase: 

    /// <summary> 缓冲任务抽象基类 </summary>public abstract class BufferPlayEntityBase : IBufferPlayEntity{/// <summary> 执行状态 1=正在执行 2=执行完成  0=未执行 -1=执行错误 </summary>public int IsLoaded { get; set; }public void Start(){this.IsLoaded = 1;try{this.DoStart();}catch (Exception ex){Debug.WriteLine(ex);this.IsLoaded = -1;}this.IsLoaded = 2;}public abstract void DoStart();}

GitHub:

这篇关于示例:WPF中Slider控件封装的缓冲播放进度条控件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1005034

相关文章

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

Golang如何对cron进行二次封装实现指定时间执行定时任务

《Golang如何对cron进行二次封装实现指定时间执行定时任务》:本文主要介绍Golang如何对cron进行二次封装实现指定时间执行定时任务问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录背景cron库下载代码示例【1】结构体定义【2】定时任务开启【3】使用示例【4】控制台输出总结背景

C++11作用域枚举(Scoped Enums)的实现示例

《C++11作用域枚举(ScopedEnums)的实现示例》枚举类型是一种非常实用的工具,C++11标准引入了作用域枚举,也称为强类型枚举,本文主要介绍了C++11作用域枚举(ScopedEnums... 目录一、引言二、传统枚举类型的局限性2.1 命名空间污染2.2 整型提升问题2.3 类型转换问题三、C

Java实现自定义table宽高的示例代码

《Java实现自定义table宽高的示例代码》在桌面应用、管理系统乃至报表工具中,表格(JTable)作为最常用的数据展示组件,不仅承载对数据的增删改查,还需要配合布局与视觉需求,而JavaSwing... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码

C++ 检测文件大小和文件传输的方法示例详解

《C++检测文件大小和文件传输的方法示例详解》文章介绍了在C/C++中获取文件大小的三种方法,推荐使用stat()函数,并详细说明了如何设计一次性发送压缩包的结构体及传输流程,包含CRC校验和自动解... 目录检测文件的大小✅ 方法一:使用 stat() 函数(推荐)✅ 用法示例:✅ 方法二:使用 fsee

mysql查询使用_rowid虚拟列的示例

《mysql查询使用_rowid虚拟列的示例》MySQL中,_rowid是InnoDB虚拟列,用于无主键表的行ID查询,若存在主键或唯一列,则指向其,否则使用隐藏ID(不稳定),推荐使用ROW_NUM... 目录1. 基本查询(适用于没有主键的表)2. 检查表是否支持 _rowid3. 注意事项4. 最佳实

HTML中meta标签的常见使用案例(示例详解)

《HTML中meta标签的常见使用案例(示例详解)》HTMLmeta标签用于提供文档元数据,涵盖字符编码、SEO优化、社交媒体集成、移动设备适配、浏览器控制及安全隐私设置,优化页面显示与搜索引擎索引... 目录html中meta标签的常见使用案例一、基础功能二、搜索引擎优化(seo)三、社交媒体集成四、移动