简体   繁体   English

C#WPF调用Windows Media Player

[英]C# WPF Invoking Windows Media Player

I'm currently passing my time by creating a piano app. 我目前正在通过创建钢琴应用程序来打发时间。 Each Key is represented of a simple button with a command which fires at click. 每个按键都由一个简单的按钮表示,该按钮带有一个可在单击时触发的命令。 This leads to executing this Method in ViewModel: 这导致在ViewModel中执行以下方法:

    private void PlaySound(object parameter)
    {
        var mediaPlayer = new MediaPlayer();
        mediaPlayer.Open(new System.Uri(@SoundBar.GetSoundPathByIdent(int.Parse(parameter.ToString()))));
        mediaPlayer.Play();
    {

I think the problem is that the MediaPlayer does not leave a WeakReference which prevents the GarbageCollector from collecting it. 我认为问题在于MediaPlayer不会留下WeakReference,这会阻止GarbageCollector收集它。 Leading to overloading your RAM after playing a while. 播放一段时间后导致RAM超载。

The solution i found was to call: mediaPlayer.Close(); 我找到的解决方案是调用: mediaPlayer.Close(); But this should only happen after the sound has finished playing, otherwise it will be cut. 但这仅应在声音播放完毕后进行,否则将被剪切。

Is there a way to check if the played sound has finished playing? 有没有办法检查播放的声音是否已经播放完毕?

I have already spent some time doing research and testing but i couldn't come up with a working solution. 我已经花了一些时间进行研究和测试,但是我无法提出一个可行的解决方案。

The Position and NaturalDuration properties give you details about where in the stream you're at (ie. Position / NaturalDuration gives you a value between 0.0 and 1.0 that represents the playback position as a percentage) PositionNaturalDuration属性为您提供有关流所在位置的详细信息(即Position / NaturalDuration为您提供介于0.0和1.0之间的值,以百分比表示播放位置)

But you may want to build an "orchestrator" for your media playback. 但是您可能想为媒体播放构建一个“编排器”。 Assuming that you don't want to play all sounds at the same time, an orchestrator could be responsible for managing the lifetime of your media players, and determining where in the playback they are. 假设您不想同时播放所有声音,则协调器可能负责管理媒体播放器的寿命,并确定它们在播放中的位置。

In your application you could create a single instance of the orchestrator on start up. 在您的应用程序中,您可以在启动时创建业务流程的单个实例。 The orchestrator could create and manage a pool of media players it could reuse when it needs to play a chord. 协调器可以创建和管理一个媒体播放器池,在需要播放和弦时可以重复使用。 Then your piano app could support a certain number of chords at the same time and have a single poller that determines which media players are free and which are "busy" playing audio. 然后,您的钢琴应用程序可以同时支持一定数量的和弦,并具有一个轮询器,该轮询器可以确定哪些媒体播放器是免费的,哪些媒体播放器“忙”着播放音频。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM