基于WPF实现一个简单的音频播放动画控件

1.实现代码

一、创建AnimationAudio.xaml代码如下



    
        
        
    

    

    
        
        
        
        
        
        
            
                
                    
                        
                            
                                
                            
                            
                                
                            

                            
                                
                            
                            
                                
                            
                        
                    
                    
                        
                            
                                
                                
                            
                            
                                
                                
                                
                                
                            
                            
                                
                            
                        
                    
                    
                        
                            
                                
                            
                            
                                
                            
                        
                        
                            
                            
                            
                            
                            
                                
                                    
                                        
                                    
                                
                            
                        
                    
                
            
        
    


二、创建AnimationAudioe.cs代码如下

using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Interop;
using WPFDevelopers.Helpers;

namespace WPFDevelopers.Controls
{
    [TemplatePart(Name = RunTemplateName, Type = typeof(Run))]
    public partial class AnimationAudio : Control
    {
        const string RunTemplateName = "PART_RunTimeLength";

        private Run _run;
        private TimeSpan _timeSpan;
        private IntPtr _handle;
        private AudioWindow _win = null;

        static string[] mediaExtensions = { ".MP3", ".WAV" };
        /// 
        /// 音频路径
        /// 
        public string AudioPath
        {
            get { return (string)GetValue(AudioPathProperty); }
            set { SetValue(AudioPathProperty, value); }
        }
        public static readonly DependencyProperty AudioPathProperty =
            DependencyProperty.Register("AudioPath", typeof(string), typeof(AnimationAudio), new PropertyMetadata(string.Empty));

        /// 
        /// 是否右侧
        /// 
        public bool IsRight
        {
            get { return (bool)GetValue(IsRightProperty); }
            set { SetValue(IsRightProperty, value); }
        }
        public static readonly DependencyProperty IsRightProperty =
            DependencyProperty.Register("IsRight", typeof(bool), typeof(AnimationAudio), new PropertyMetadata(false));

        public bool IsPlay
        {
            get { return (bool)GetValue(IsPlayProperty); }
            set { SetValue(IsPlayProperty, value); }
        }

        public static readonly DependencyProperty IsPlayProperty =
            DependencyProperty.Register("IsPlay", typeof(bool), typeof(AnimationAudio), new PropertyMetadata(false, new PropertyChangedCallback(OnIsPlayChanged)));

        private static void OnIsPlayChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            bool newValue = (bool)e.NewValue;
            var animationAudio = d as AnimationAudio;
            if(newValue != (bool)e.OldValue)
            {
                if (newValue)
                {
                    animationAudio.Play();
                }
                else
                {
                    AudioPlayer.Stop();
                }
            }
        }

        static AnimationAudio()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(AnimationAudio), new FrameworkPropertyMetadata(typeof(AnimationAudio)));
        }

       
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            _run = GetTemplateChild(RunTemplateName) as Run;
            if (string.IsNullOrWhiteSpace(AudioPath)) return;
            if (!File.Exists(AudioPath)) return;
            if (!mediaExtensions.Contains(Path.GetExtension(AudioPath), StringComparer.OrdinalIgnoreCase)) return;
            _timeSpan = AudioPlayer.GetSoundLength(AudioPath);
            if (_timeSpan == TimeSpan.Zero) return;
            _run.Text = $"{_timeSpan.Seconds.ToString()}\"";
            Width = 80;
            if (_timeSpan.Seconds > 5)
            {
                Width += _timeSpan.Seconds;
            }
        }

        private void Play()
        {
            if(_win != null)
            {
                _win.Close();
                _win = null;
            }
            _win = new AudioWindow
            {
                Width = 0,
                Height = 0,
                Left = Int32.MinValue,
                Top = Int32.MinValue,
                WindowStyle = WindowStyle.None,
                ShowInTaskbar = false,
                ShowActivated = false,
            };
            _win.Show();
            _win.StopDelegateEvent += _win_StopDelegateEvent;
            _handle = new WindowInteropHelper(_win).Handle;
            AudioPlayer.PlaySong(AudioPath, _handle);
        }

       
        private void _win_StopDelegateEvent()
        {
            IsPlay = false;
            _win.Close();
            _win = null;
        }
    }
}

三、新建AudioWindow.cs代码如下

using System;
using System.Windows;
using System.Windows.Interop;

namespace WPFDevelopers.Controls
{
    public class AudioWindow:Window
    {
        const int MM_MCINOTIFY = 0x3B9;
        public delegate void StopDelegate();
        public event StopDelegate StopDelegateEvent;
        
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
            if (hwndSource != null)
            {
                hwndSource.AddHook(new HwndSourceHook(this.WndProc));
            }
        }
        
        IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            switch (msg)
            {
                case MM_MCINOTIFY:
                    StopDelegateEvent?.Invoke();
                    break;
            }
            return IntPtr.Zero;
        }
    }
}

四、新建AnimationAudioExample.xaml代码如下。

  

    
        
            
                
                    
                        
                    
                
            
            
        
        
            
            
                
                    
                        
                    
                
            
        
       
    

                 

六、新建AnimationAudioExample.xaml.cs下

using System;
using System.IO;
using System.Windows.Controls;
using WPFDevelopers.Controls;
using WPFDevelopers.Samples.Helpers;

namespace WPFDevelopers.Samples.ExampleViews
{
    /// 
    /// 微信公众号:WPF开发者
    /// 
    public partial class AnimationAudioExample : UserControl
    {
        public AnimationAudioExample()
        {
            InitializeComponent();
            AnimationAudioLeft.AudioPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "Audio", "HelloWPFDevelopes_en.mp3");
            AnimationAudioRight.AudioPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "Audio", "HelloWPFDevelopes_zh.mp3");
        }

        private void AnimationAudioLeft_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var animationAudio = sender as AnimationAudio;
            var animationAudioList = ElementVisualTreeHelper.FindVisualChild(MyUniformGrid);
            if (animationAudioList == null) return;
            if (!animationAudio.IsPlay)
            {
                animationAudioList.ForEach(h =>
                {
                    if (h.IsPlay && h != animationAudio)
                    {
                        h.IsPlay = false;
                    }
                });
                animationAudio.IsPlay = true;
            }
            else
                animationAudio.IsPlay = false;
        }
    }
}

2.效果预览

基于WPF实现一个简单的音频播放动画控件_第1张图片

到此这篇关于基于WPF实现一个简单的音频播放动画控件的文章就介绍到这了,更多相关WPF音频播放动画控件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(基于WPF实现一个简单的音频播放动画控件)