A WPF Spectrum Analyzer for Audio Visualization (C#) – Part 2: The WPFening
UPDATE:The WPF Spectrum Analyzer is now part of the WPF Sound Visualization Library. That is where you will find source code for the latest and most-stable versions of the Spectrum Analyzer.
—
A number of weeks ago, I shared with the world a WPF Spectrum Analyzer UserControl I had created. This post is an update on that. Why is there an update? Well, I’ve made some pretty fundamental changes to the Spectrum Analyzer. Not changes that an end-user would necessarily notice at first glance, but they’re fundamental to the way the control performs. I was dissatisfied with the first iteration of the Spectrum Analyzer for two reasons:
- It didn’t support scaling.
- It was a UserControl, which means that didn’t support custom templates/themes.
These two inadequacies severely crippled much of what makes WPF so great.
Supporting Scaling – Go Go Gadget Vectors!
My first pass at the Spectrum Analyzer was based on a very bad assumption. I assumed, foolishly, that a classic pixel-based rendering loop where I manually controlled the buffers would offer me performance benefits and control that I would not be able to achieve if I used vector-based rendering techniques. When I say “vector-based” I mean rendering Shapes on a Canvas. “Pixel-based” refers to me using a DrawingContext to draw shapes in a fashion similar to how things were done in the ol’ GDI+ days. I’ve left my old post in tact if you want to see how the pixel-based technique was done. Assumption aside, using pixel-based rendering has some consequences when a ScaleTransform gets applied to my control. Basically, things get blurry. It’s the same as resizing an image in Photoshop (that is, in the real world, where we don’t have CSI-like “enhance” commands). Since I’m a big proponent of using ScaleTransforms to “zoom” in on a Window’s content as the Window resizes, I felt like this inadequacy in my control was eating away at my soul.
To set about changing this, I had to first mentally break down the control into vector components. Luckily, the Spectrum Analyzer isn’t terribly complex. It’s essentially a variable number of rectangles laid out horizontally. Then, added to that, is another set of rectangles (of the same quantity) that make up the “falling peaks.”
Template Support
This brings us to crafting the control as an ACTUAL Control rather than a UserControl. Really, the only component I require is a Canvas on which I can draw all these Rectangles. I’ve set up my Control using the conventional “PART_” naming convention (see TemplatePartAttribute). To actually get the bars or falling peaks to draw, an application author will also need to define the BarStyle and/or PeakStyle dependency properties on the control. Without these, they’ll still technically “draw,” but they’ll have no brush and be invisible.
Here’s an example of a style and template for the SpectrumAnalyzer control.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | <LinearGradientBrush x:Key="SpectrumBarBrush" EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#06799F" Offset="0" /> <GradientStop Color="#024E68" Offset="1" /> </LinearGradientBrush> <SolidColorBrush x:Key="SpectrumPeakBrush" Color="#61B4CF" /> <Style TargetType="{x:Type local:SpectrumAnalyzer}"> <Setter Property="BarCount" Value="32" /> <Setter Property="BarSpacing" Value="5" /> <Setter Property="BarStyle"> <Setter.Value> <Style TargetType="{x:Type Rectangle}"> <Setter Property="Fill" Value="{StaticResource SpectrumBarBrush}" /> <Setter Property="RadiusX" Value="3" /> <Setter Property="RadiusY" Value="3" /> </Style> </Setter.Value> </Setter> <Setter Property="PeakStyle"> <Setter.Value> <Style TargetType="{x:Type Rectangle}"> <Setter Property="Fill" Value="{StaticResource SpectrumPeakBrush}" /> <Setter Property="RadiusX" Value="3" /> <Setter Property="RadiusY" Value="3" /> </Style> </Setter.Value> </Setter> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:SpectrumAnalyzer}"> <Canvas Name="PART_SpectrumCanvas" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ClipToBounds="True" /> </ControlTemplate> </Setter.Value> </Setter> </Style> |
Revised Control Code
I’ve revised the rendering process a bit. When I first wrote the control code, there was a render method that drew a bunch of rectangles onto a DrawingVisual. Instead of drawing directly, I now just change the coordinates/size of a bunch of rectangles that are stored as fields on the Spectrum Analyzer. I let WPF handle their rendering. Thus, my “RenderSpectrumLines” method became a “UpdateSpectrumShapes” method. Also, since this is now a control, there is no XAML to go along with it per se. However, there would be a default template for it if it were placed in a Control Library. Here’s the updated code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 | [TemplatePart(Name = "PART_SpectrumCanvas", Type = typeof(Canvas))] public class SpectrumAnalyzer : Control { #region Fields private readonly DispatcherTimer animationTimer; private Canvas spectrumCanvas; private ISpectrumPlayer soundPlayer; private readonly List<Shape> barShapes = new List<Shape>(); private readonly List<Shape> peakShapes = new List<Shape>(); private double[] barHeights; private double[] peakHeights; private float[] channelData = new float[2048]; private float[] channelPeakData; private double bandWidth = 1.0; private double barWidth = 1; private int maximumFrequencyIndex = 2047; private int minimumFrequencyIndex; private int[] barIndexMax; private int[] barLogScaleIndexMax; #endregion #region Constants private const int scaleFactorLinear = 9; private const int scaleFactorSqr = 2; private const double minDBValue = -90; private const double maxDBValue = 0; private const double dbScale = (maxDBValue - minDBValue); #endregion #region Dependency Properties #region MaximumFrequency public static readonly DependencyProperty MaximumFrequencyProperty = DependencyProperty.Register("MaximumFrequency", typeof(int), typeof(SpectrumAnalyzer), new UIPropertyMetadata(20000, OnMaximumFrequencyChanged, OnCoerceMaximumFrequency)); private static object OnCoerceMaximumFrequency(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoerceMaximumFrequency((int)value); else return value; } private static void OnMaximumFrequencyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnMaximumFrequencyChanged((int)e.OldValue, (int)e.NewValue); } protected virtual int OnCoerceMaximumFrequency(int value) { if ((int)value < MinimumFrequency) return MinimumFrequency + 1; return value; } protected virtual void OnMaximumFrequencyChanged(int oldValue, int newValue) { UpdateBarLayout(); } /// <summary> /// The maximum display frequency (right side) for the spectrum analyzer. /// </summary> /// <remarks>In usual practice, this value should be somewhere between 0 and half of the maximum sample rate. If using /// the maximum sample rate, this would be roughly 22000.</remarks> [Category("Common")] public int MaximumFrequency { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (int)GetValue(MaximumFrequencyProperty); } set { SetValue(MaximumFrequencyProperty, value); } } #endregion #region Minimum Frequency public static readonly DependencyProperty MinimumFrequencyProperty = DependencyProperty.Register("MinimumFrequency", typeof(int), typeof(SpectrumAnalyzer), new UIPropertyMetadata(20, OnMinimumFrequencyChanged, OnCoerceMinimumFrequency)); private static object OnCoerceMinimumFrequency(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoerceMinimumFrequency((int)value); else return value; } private static void OnMinimumFrequencyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnMinimumFrequencyChanged((int)e.OldValue, (int)e.NewValue); } protected virtual int OnCoerceMinimumFrequency(int value) { if (value < 0) return value = 0; CoerceValue(MaximumFrequencyProperty); return value; } protected virtual void OnMinimumFrequencyChanged(int oldValue, int newValue) { UpdateBarLayout(); } /// <summary> /// The minimum display frequency (left side) for the spectrum analyzer. /// </summary> [Category("Common")] public int MinimumFrequency { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (int)GetValue(MinimumFrequencyProperty); } set { SetValue(MinimumFrequencyProperty, value); } } #endregion #region BarCount public static readonly DependencyProperty BarCountProperty = DependencyProperty.Register("BarCount", typeof(int), typeof(SpectrumAnalyzer), new UIPropertyMetadata(32, OnBarCountChanged, OnCoerceBarCount)); private static object OnCoerceBarCount(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoerceBarCount((int)value); else return value; } private static void OnBarCountChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnBarCountChanged((int)e.OldValue, (int)e.NewValue); } protected virtual int OnCoerceBarCount(int value) { value = Math.Max(value, 1); return value; } protected virtual void OnBarCountChanged(int oldValue, int newValue) { UpdateBarLayout(); } /// <summary> /// The number of bars to show on the sprectrum analyzer. /// </summary> /// <remarks>A bar's width can be a minimum of 1 pixel. If the BarSpacing and BarCount property result /// in the bars being wider than the chart itself, the BarCount will automatically scale down.</remarks> [Category("Common")] public int BarCount { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (int)GetValue(BarCountProperty); } set { SetValue(BarCountProperty, value); } } #endregion #region BarSpacing public static readonly DependencyProperty BarSpacingProperty = DependencyProperty.Register("BarSpacing", typeof(double), typeof(SpectrumAnalyzer), new UIPropertyMetadata(5.0d, OnBarSpacingChanged, OnCoerceBarSpacing)); private static object OnCoerceBarSpacing(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoerceBarSpacing((double)value); else return value; } private static void OnBarSpacingChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnBarSpacingChanged((double)e.OldValue, (double)e.NewValue); } protected virtual double OnCoerceBarSpacing(double value) { value = Math.Max(value, 0); return value; } protected virtual void OnBarSpacingChanged(double oldValue, double newValue) { UpdateBarLayout(); } /// <summary> /// The spacing, in pixels, between the bars. /// </summary> [Category("Common")] public double BarSpacing { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (double)GetValue(BarSpacingProperty); } set { SetValue(BarSpacingProperty, value); } } #endregion #region PeakFallDelay public static readonly DependencyProperty PeakFallDelayProperty = DependencyProperty.Register("PeakFallDelay", typeof(int), typeof(SpectrumAnalyzer), new UIPropertyMetadata(10, OnPeakFallDelayChanged, OnCoercePeakFallDelay)); private static object OnCoercePeakFallDelay(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoercePeakFallDelay((int)value); else return value; } private static void OnPeakFallDelayChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnPeakFallDelayChanged((int)e.OldValue, (int)e.NewValue); } protected virtual int OnCoercePeakFallDelay(int value) { value = Math.Max(value, 0); return value; } protected virtual void OnPeakFallDelayChanged(int oldValue, int newValue) { } /// <summary> /// The delay factor for the peaks falling. This is relative to the /// refresh rate of the chart. /// </summary> [Category("Common")] public int PeakFallDelay { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (int)GetValue(PeakFallDelayProperty); } set { SetValue(PeakFallDelayProperty, value); } } #endregion #region IsFrequencyScaleLinear public static readonly DependencyProperty IsFrequencyScaleLinearProperty = DependencyProperty.Register("IsFrequencyScaleLinear", typeof(bool), typeof(SpectrumAnalyzer), new UIPropertyMetadata(false, OnIsFrequencyScaleLinearChanged, OnCoerceIsFrequencyScaleLinear)); private static object OnCoerceIsFrequencyScaleLinear(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoerceIsFrequencyScaleLinear((bool)value); else return value; } private static void OnIsFrequencyScaleLinearChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnIsFrequencyScaleLinearChanged((bool)e.OldValue, (bool)e.NewValue); } protected virtual bool OnCoerceIsFrequencyScaleLinear(bool value) { return value; } protected virtual void OnIsFrequencyScaleLinearChanged(bool oldValue, bool newValue) { UpdateBarLayout(); } /// <summary> /// If true, the bars will represent frequency buckets on a linear scale (making them all /// have equal band widths on the frequency scale). Otherwise, the bars will be layed out /// on a logrithmic scale, with each bar having a larger bandwidth than the one previous. /// </summary> [Category("Common")] public bool IsFrequencyScaleLinear { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (bool)GetValue(IsFrequencyScaleLinearProperty); } set { SetValue(IsFrequencyScaleLinearProperty, value); } } #endregion #region BarHeightScaling public static readonly DependencyProperty BarHeightScalingProperty = DependencyProperty.Register("BarHeightScaling", typeof(BarHeightScalingStyles), typeof(SpectrumAnalyzer), new UIPropertyMetadata(BarHeightScalingStyles.Decibel, OnBarHeightScalingChanged, OnCoerceBarHeightScaling)); private static object OnCoerceBarHeightScaling(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoerceBarHeightScaling((BarHeightScalingStyles)value); else return value; } private static void OnBarHeightScalingChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnBarHeightScalingChanged((BarHeightScalingStyles)e.OldValue, (BarHeightScalingStyles)e.NewValue); } protected virtual BarHeightScalingStyles OnCoerceBarHeightScaling(BarHeightScalingStyles value) { return value; } protected virtual void OnBarHeightScalingChanged(BarHeightScalingStyles oldValue, BarHeightScalingStyles newValue) { } /// <summary> /// If true, the bar height will be displayed linearly with the intensity value. /// Otherwise, the bars will be scaled with a square root function. /// </summary> [Category("Common")] public BarHeightScalingStyles BarHeightScaling { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (BarHeightScalingStyles)GetValue(BarHeightScalingProperty); } set { SetValue(BarHeightScalingProperty, value); } } #endregion #region AveragePeaks public static readonly DependencyProperty AveragePeaksProperty = DependencyProperty.Register("AveragePeaks", typeof(bool), typeof(SpectrumAnalyzer), new UIPropertyMetadata(false, OnAveragePeaksChanged, OnCoerceAveragePeaks)); private static object OnCoerceAveragePeaks(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoerceAveragePeaks((bool)value); else return value; } private static void OnAveragePeaksChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnAveragePeaksChanged((bool)e.OldValue, (bool)e.NewValue); } protected virtual bool OnCoerceAveragePeaks(bool value) { return value; } protected virtual void OnAveragePeaksChanged(bool oldValue, bool newValue) { } /// <summary> /// If true, each bar's peak value will be averaged with the previous /// bar's peak. This creates a smoothing effect on the bars. /// </summary> [Category("Common")] public bool AveragePeaks { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (bool)GetValue(AveragePeaksProperty); } set { SetValue(AveragePeaksProperty, value); } } #endregion #region BarStyle public static readonly DependencyProperty BarStyleProperty = DependencyProperty.Register("BarStyle", typeof(Style), typeof(SpectrumAnalyzer), new UIPropertyMetadata(null, new PropertyChangedCallback(OnBarStyleChanged), new CoerceValueCallback(OnCoerceBarStyle))); private static object OnCoerceBarStyle(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoerceBarStyle((Style)value); else return value; } private static void OnBarStyleChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnBarStyleChanged((Style)e.OldValue, (Style)e.NewValue); } protected virtual Style OnCoerceBarStyle(Style value) { return value; } protected virtual void OnBarStyleChanged(Style oldValue, Style newValue) { UpdateBarLayout(); } /// <summary> /// A style with which to draw the bars on the spectrum analyzer. /// </summary> public Style BarStyle { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (Style)GetValue(BarStyleProperty); } set { SetValue(BarStyleProperty, value); } } #endregion #region PeakStyle public static readonly DependencyProperty PeakStyleProperty = DependencyProperty.Register("PeakStyle", typeof(Style), typeof(SpectrumAnalyzer), new UIPropertyMetadata(null, new PropertyChangedCallback(OnPeakStyleChanged), new CoerceValueCallback(OnCoercePeakStyle))); private static object OnCoercePeakStyle(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoercePeakStyle((Style)value); else return value; } private static void OnPeakStyleChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnPeakStyleChanged((Style)e.OldValue, (Style)e.NewValue); } protected virtual Style OnCoercePeakStyle(Style value) { return value; } protected virtual void OnPeakStyleChanged(Style oldValue, Style newValue) { UpdateBarLayout(); } /// <summary> /// A style with which to draw the falling peaks on the spectrum analyzer. /// </summary> public Style PeakStyle { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (Style)GetValue(PeakStyleProperty); } set { SetValue(PeakStyleProperty, value); } } #endregion #region ActualBarWidth public static readonly DependencyProperty ActualBarWidthProperty = DependencyProperty.Register("ActualBarWidth", typeof(double), typeof(SpectrumAnalyzer), new UIPropertyMetadata(0.0d, new PropertyChangedCallback(OnActualBarWidthChanged), new CoerceValueCallback(OnCoerceActualBarWidth))); private static object OnCoerceActualBarWidth(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoerceActualBarWidth((double)value); else return value; } private static void OnActualBarWidthChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnActualBarWidthChanged((double)e.OldValue, (double)e.NewValue); } protected virtual double OnCoerceActualBarWidth(double value) { return value; } protected virtual void OnActualBarWidthChanged(double oldValue, double newValue) { } /// <summary> /// The actual width that the bars will be drawn at. /// </summary> public double ActualBarWidth { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (double)GetValue(ActualBarWidthProperty); } protected set { SetValue(ActualBarWidthProperty, value); } } #endregion #endregion #region Enums /// <summary> /// The different ways that the bar height can be scaled by the spectrum analyzer. /// </summary> public enum BarHeightScalingStyles { /// <summary> /// A decibel scale. Formula: 20 * Log10(FFTValue). Total bar height /// is scaled from -90 to 0 dB. /// </summary> Decibel, /// <summary> /// A non-linear squareroot scale. Formula: Sqrt(FFTValue) * 2 * BarHeight. /// </summary> Sqrt, /// <summary> /// A linear scale. Formula: 9 * FFTValue * BarHeight. /// </summary> Linear } /// <summary> /// The styles that the spectrum analyzer can draw the bars. /// </summary> public enum BarDrawingStyles { /// <summary> /// Square bars. /// </summary> Square, /// <summary> /// Rounded bars with the corner radius as half the /// bar width. /// </summary> Rounded } #endregion #region Template Overrides public override void OnApplyTemplate() { spectrumCanvas = GetTemplateChild("PART_SpectrumCanvas") as Canvas; UpdateBarLayout(); } #endregion #region Constructors static SpectrumAnalyzer() { DefaultStyleKeyProperty.OverrideMetadata(typeof(SpectrumAnalyzer), new FrameworkPropertyMetadata(typeof(SpectrumAnalyzer))); } public SpectrumAnalyzer() { animationTimer = new DispatcherTimer(DispatcherPriority.ApplicationIdle) { Interval = TimeSpan.FromMilliseconds(25), }; animationTimer.Tick += animationTimer_Tick; } #endregion #region Public Methods /// <summary> /// Register a sound player from which the spectrum analyzer /// can get the necessary playback data. /// </summary> /// <param name="soundPlayer">A sound player that provides spectrum data through the ISpectrumPlayer interface methods.</param> public void RegisterSoundPlayer(ISpectrumPlayer soundPlayer) { this.soundPlayer = soundPlayer; soundPlayer.PropertyChanged += soundPlayer_PropertyChanged; UpdateBarLayout(); animationTimer.Start(); } #endregion #region Event Overrides protected override void OnRender(DrawingContext dc) { base.OnRender(dc); UpdateBarLayout(); UpdateSpectrum(); } protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) { base.OnRenderSizeChanged(sizeInfo); UpdateBarLayout(); UpdateSpectrum(); } #endregion #region Private Drawing Methods private void UpdateSpectrum() { if (soundPlayer == null || spectrumCanvas == null || spectrumCanvas.RenderSize.Width < 1 || spectrumCanvas.RenderSize.Height < 1) return; if (soundPlayer.IsPlaying && (soundPlayer.GetFFTData(channelData) < 1)) return; UpdateSpectrumShapes(); } private void UpdateSpectrumShapes() { bool allZero = true; double fftBucketHeight = 0f; double barHeight = 0f; double lastPeakHeight = 0f; double peakYPos = 0f; double height = spectrumCanvas.RenderSize.Height; int barIndex = 0; double peakDotHeight = Math.Max(barWidth / 2.0f, 1); double barHeightScale = (height - peakDotHeight); for (int i = minimumFrequencyIndex; i <= maximumFrequencyIndex; i++) { // If we're paused, keep drawing, but set the current height to 0 so the peaks fall. if (!soundPlayer.IsPlaying) { barHeight = 0f; } else // Draw the maximum value for the bar's band { switch (BarHeightScaling) { case BarHeightScalingStyles.Decibel: double dbValue = 20 * Math.Log10((double)channelData[i]); fftBucketHeight = ((dbValue - minDBValue) / dbScale) * barHeightScale; break; case BarHeightScalingStyles.Linear: fftBucketHeight = (channelData[i] * scaleFactorLinear) * barHeightScale; break; case BarHeightScalingStyles.Sqrt: fftBucketHeight = (((Math.Sqrt((double)channelData[i])) * scaleFactorSqr) * barHeightScale); break; } if (barHeight < fftBucketHeight) barHeight = fftBucketHeight; if (barHeight < 0f) barHeight = 0f; } // If this is the last FFT bucket in the bar's group, draw the bar. int currentIndexMax = IsFrequencyScaleLinear ? barIndexMax[barIndex] : barLogScaleIndexMax[barIndex]; if (i == currentIndexMax) { // Peaks can't surpass the height of the control. if (barHeight > height) barHeight = height; if (AveragePeaks && barIndex > 0) barHeight = (lastPeakHeight + barHeight) / 2; peakYPos = barHeight; if (channelPeakData[barIndex] < peakYPos) channelPeakData[barIndex] = (float)peakYPos; else channelPeakData[barIndex] = (float)(peakYPos + (PeakFallDelay * channelPeakData[barIndex])) / ((float)(PeakFallDelay + 1)); double xCoord = BarSpacing + (barWidth * barIndex) + (BarSpacing * barIndex) + 1; barShapes[barIndex].Margin = new Thickness(xCoord, (height - 1) - barHeight, 0, 0); barShapes[barIndex].Height = barHeight; peakShapes[barIndex].Margin = new Thickness(xCoord, (height - 1) - channelPeakData[barIndex] - peakDotHeight, 0, 0); peakShapes[barIndex].Height = peakDotHeight; if (channelPeakData[barIndex] > 0.05) allZero = false; lastPeakHeight = barHeight; barHeight = 0f; barIndex++; } } if (allZero && !soundPlayer.IsPlaying) animationTimer.Stop(); } private void UpdateBarLayout() { if (soundPlayer == null || spectrumCanvas == null) return; barWidth = Math.Max(((double)(spectrumCanvas.RenderSize.Width - (BarSpacing * (BarCount + 1))) / (double)BarCount), 1); maximumFrequencyIndex = Math.Min(soundPlayer.GetFFTFrequencyIndex(MaximumFrequency) + 1, 2047); minimumFrequencyIndex = Math.Min(soundPlayer.GetFFTFrequencyIndex(MinimumFrequency), 2047); bandWidth = Math.Max(((double)(maximumFrequencyIndex - minimumFrequencyIndex)) / spectrumCanvas.RenderSize.Width, 1.0); int actualBarCount; if (barWidth >= 1.0d) actualBarCount = BarCount; else actualBarCount = Math.Max((int)((spectrumCanvas.RenderSize.Width - BarSpacing) / (barWidth + BarSpacing)), 1); channelPeakData = new float[actualBarCount]; int indexCount = maximumFrequencyIndex - minimumFrequencyIndex; int linearIndexBucketSize = (int)Math.Round((double)indexCount / (double)actualBarCount, 0); List<int> maxIndexList = new List<int>(); List<int> maxLogScaleIndexList = new List<int>(); double maxLog = Math.Log(actualBarCount, actualBarCount); for (int i = 1; i < actualBarCount; i++) { maxIndexList.Add(minimumFrequencyIndex + (i * linearIndexBucketSize)); int logIndex = (int)((maxLog - Math.Log((actualBarCount + 1) - i, (actualBarCount + 1))) * indexCount) + minimumFrequencyIndex; maxLogScaleIndexList.Add(logIndex); } maxIndexList.Add(maximumFrequencyIndex); maxLogScaleIndexList.Add(maximumFrequencyIndex); barIndexMax = maxIndexList.ToArray(); barLogScaleIndexMax = maxLogScaleIndexList.ToArray(); barHeights = new double[actualBarCount]; peakHeights = new double[actualBarCount]; spectrumCanvas.Children.Clear(); barShapes.Clear(); peakShapes.Clear(); double height = spectrumCanvas.RenderSize.Height; double peakDotHeight = Math.Max(barWidth / 2.0f, 1); for (int i = 0; i < actualBarCount; i++) { double xCoord = BarSpacing + (barWidth * i) + (BarSpacing * i) + 1; Rectangle barRectangle = new Rectangle() { Margin = new Thickness(xCoord, height, 0, 0), Width = barWidth, Height = 0, Style = BarStyle }; barShapes.Add(barRectangle); Rectangle peakRectangle = new Rectangle() { Margin = new Thickness(xCoord, height - peakDotHeight, 0, 0), Width = barWidth, Height = peakDotHeight, Style = PeakStyle }; peakShapes.Add(peakRectangle); } foreach (Shape shape in barShapes) spectrumCanvas.Children.Add(shape); foreach (Shape shape in peakShapes) spectrumCanvas.Children.Add(shape); ActualBarWidth = barWidth; } #endregion #region Event Handlers private void soundPlayer_PropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case "IsPlaying": if (soundPlayer.IsPlaying && !animationTimer.IsEnabled) animationTimer.Start(); break; } } private void animationTimer_Tick(object sender, EventArgs e) { UpdateSpectrum(); } #endregion } |
On Performance / Conclusion
So, where does this leave us? A peak at the Task Manager delivers a pretty telling tale. On my system, the control continues to use very little processor power. What’s even better, however, is you’ll see far less churning of the memory usage. It seems that when you let WPF handle the rendering, it gets to have better control of what sort of buffers get created and how quickly they’re cleared from memory. When we did it manually with our RenderTargetBitmap, we were at the mercy of the garbage collector.
I think there are still a number of controls where one will need to fall back on to pixel based rendering (e.g., a spectrogram), but this one lent itself well to being drawn with vectors. That said, I think the current iteration of this Control is far closer to how one should design their controls for other people to use. People incorporating this into their own applications should find it much more flexible in style, as well as much more performant.