问题描述
这是我的第一个 C# 程序,很抱歉没有经验。
这个 Windows 窗体应用程序旨在成为一个 mp3 播放器,从其目录中收集 mp3 文件并一个一个播放。
每当我按下“BtnNext”按钮播放下一首歌曲时,应用程序的 cpu 使用率会高达 20%,然后应用程序停止响应。几秒钟后,一切恢复正常。
作为后台应用,我希望它尽可能使用最少的资源
应用代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using WMPLib;
using System.IO;
namespace SongReader
{
public partial class Form1 : Form
{
WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
string[] music = { };
public Form1()
{
InitializeComponent();
ThreadPool.QueueUserWorkItem(GetSongs);
//in theory this executes GetSongs on another Thread,so that the app can still be functional
wplayer.MediaChange += Songdisplay; //calls Songdisplay function whenever the media that's being played changes
}
public void GetSongs(object state)
{
string dir = Directory.GetCurrentDirectory();
music = Directory.GetFiles(dir,"*.mp3",SearchOption.AllDirectories); //takes all mp3 files from its directory
wplayer.settings.setMode("loop",true);
foreach (string file in music)
{
WMPLib.IWMPMedia media = wplayer.newMedia(file);
wplayer.currentPlaylist.appendItem(media);
}
notifyIcon.Visible = false;
wplayer.settings.volume = Convert.ToInt32(numericupdown.Value);
}
//from this point on there are just the buttons
private void BtnPlay_Click(object sender,EventArgs e)
{
wplayer.controls.play();
}
private void BtnBackground_Click(object sender,EventArgs e)
{
Hide();
notifyIcon.Visible = true;//minimizes the app to the system tray
}
private void NotifyIcon_MouseClick(object sender,MouseEventArgs e)
{
Show();
notifyIcon.Visible = false; //makes the app window visible
}
private void BtnStop_MouseClick(object sender,MouseEventArgs e)
{
wplayer.controls.pause();
}
private void BtnPrevIoUs_MouseClick(object sender,MouseEventArgs e)
{
wplayer.controls.prevIoUs();
}
private void BtnNext_MouseClick(object sender,MouseEventArgs e)
{
wplayer.controls.next();
}
private void BtnResetSong_MouseClick(object sender,MouseEventArgs e)
{
wplayer.controls.stop();
}
private void numericupdown_ValueChanged(object sender,EventArgs e)
{
wplayer.settings.volume = Convert.ToInt32(numericupdown.Value); //volume controller
}
private void Songdisplay(object pdispMedia)
{
txtSongdisplay.Text = wplayer.currentMedia.name; //shows the name of the song that just started
}
}
}
我不知道这是否有帮助,但这是应用程序的外观(三个下划线将更改为歌曲名称)
经过调试后,我发现“IL_STUB_CLRtoCOM()”在程序没有响应时占用了大量cpu,但我不知道是什么原因造成的
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)