在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
要做基于WPF的音频文件循环顺序播放首先要了解WPF下有哪些类是用于控制音频的. MediaElement类同MediaPlayer的功能类似,作为WPF页面可用的标签是MediaPlayer的衍生; 复制代码 代码如下: WPF界面代码 <Window x:Class="MediaApplication.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:md="clr-namespace:MediaApplication" Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded"> <StackPanel> <md:MediaManager x:Name="media"></md:MediaManager> </StackPanel> </Window> 复制代码 代码如下: WPF界面CS代码 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.IO; using System.Collections.ObjectModel; using System.Configuration; namespace MediaApplication { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { this.media.PlayList(); } } } 复制代码 代码如下: MediaManager类 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Controls; using System.IO; using System.Configuration; using System.Windows; using System.Collections.ObjectModel; namespace MediaApplication { public class MediaManager : MediaElement { public MediaManager() { try { GetAllDirList(new DirectoryInfo(ConfigurationManager.AppSettings["dir"].ToString())); } catch { } } public void PlayList() { if(files.Count > 0) { this.UnloadedBehavior = MediaState.Manual; this.LoadedBehavior = MediaState.Manual; this.MediaEnded += new RoutedEventHandler(media_MediaEnded); this.Source = new Uri( files[index], UriKind.RelativeOrAbsolute); this.Play(); } } private void GetAllDirList(DirectoryInfo directory) { foreach(string filter in filters) { foreach (FileInfo file in directory.GetFiles(filter)) { files.Add(file.FullName); } } foreach (DirectoryInfo subDirectory in directory.GetDirectories()) { GetAllDirList(subDirectory); } } private void media_MediaEnded(object sender, RoutedEventArgs e) { this.Source = new Uri( files[++index % files.Count], UriKind.RelativeOrAbsolute); this.Play(); } private ObservableCollection<string> files = new ObservableCollection<string>(); private int index = 0; private string[] filters = new string[] { "*.wav", "*.mp3" }; } } |
请发表评论