2023年12月17日发(作者:)
h
C#播放声音的四种方法
C#播放声音的四种方法
介绍之前首先推荐一个程序员专用搜索引擎-
第一种是利用DirectX
1.安装了DirectX SDK(有9个DLL文件)。这里我们只用到 和
2.引入DirectX 的DLL文件的名字空间:
using X;
using Sound;
3.建立设备
Device dv=new Device();
4.设置CooperativeLevel。因为windows是多任务的系统,设备不是独占的
SecondaryBuffer buf=new SecondaryBuffer(@"",dv);
5.开辟缓冲区SecondaryBuffer buf=new SecondaryBuffer(@"",dv);
6.接下来就可以播放啦。第一个参数表示优先级别,0是最低的。第2个参数是播放方式,这里是循环播放。
(0,g);
第二种是利用Microsoft speech object Library
/// /// 播放声音文件 ///
/// 文件全名
public void PlaySound(string FileName)
{//要加载COM组件:Microsoft speech object Library
if (!(FileName))
{
return;
}
eClass pp = new eClass();h
h
StreamClass spFs = new StreamClass();
(FileName, enForRead,
true);
hBaseStream
hBaseStream;
Istream = spFs as
tream(Istream,
Filename);
();
}
第三种:引用SoundPlayer
layer sndPlayer = new
layer(pPath+@"/");
oping();
第4种:利用Windows Media Player
新建一个C#的Windows Form工程(Windows应用程序),并且定义两个菜单按钮(menuItem1,menuItem2)。
选择菜单中的“工具”中的“自定义工具箱(添加/移除工具箱项)”,在自定义工具箱的窗口中,点击展开“COM 组件”项,选中“Window Media Player”选项。确定后在“工具箱”中便会出现“Windows Media Player”这一项,然后再将其拖至Form上,调整大小,系统在“引用”中自动加入了对此dll的引用,AxMediaPlayer就是我们使用的 Namespace与class。
在属性栏中设置好此控件的一些属性,为了方便,这里我把AutoStart设置成为true(其实默认是true),只要FileName被设置(打开了文件),则文件将会自动播放。完整代码如下:
private void menuItem1_Click(object sender, rgs e)
{h
h
OpenFileDialog ofDialog = new OpenFileDialog();
ension = true;
ileExists = true;
athExists = true;
//the next sentence must be in single line
= "VCD文件(*.dat)|*.dat|Audio文件(*.avi)|*.avi
|WAV文件(*.wav)|*.wav|MP3文件(*.mp3)|*.mp3|所有文件 (*.*)|*.*";
tExt = "*.mp3";
if(alog() == )
{
// 2003一下版本 方法 me = me;
= me;//2005用法
}
}
这里使用的是微软的播放器,大家也可以试试Winamp的控件,如果你只需要播放声音而不需要显示,你只要把AxMediaPlayer的Visible属性设置为false就可以了。
//
// (c) Copyright Jason Clark 2003
// Shows a variety of basic marshalling concepts by making
sounds
using System;
using ;
class App{
public static void Main(){
// Produce an OK beep
eBeep();
(1000);
h
h
// Ok, now for some circa-1977 si-fi
Random rand = new Random();
for( Int32 index = 0; index < 7 ; index++ )
{
( (500)+1000,
conds(.10));
}
// Pick a wave, any wave
ve( @"C:", true );
( 2000 );
ve();
}
}
namespace {
using pServices;
using entModel;
sealed class Sound{
// Friendly MessageBeep() wrapper
public static void MessageBeep(BeepTypes type) {
if( !MessageBeep( (UInt32) type ) ) {
Int32 err = tWin32Error();
throw new Win32Exception( err );
}
}
// Friendly low-level beep wrapper
public static void Beep(Int32 frequency, Int32
milliseconds) {
if(!UnmanagedBeep( (UInt32)frequency,
(UInt32)milliseconds ) ) {
Int32 err = tWin32Error();
throw new Win32Exception( err );
}
}
// Friendly low-level beep wrapper with TimeSpan
public static void Beep(Int32 frequency, TimeSpan
duration) {
Beep( frequency, (Int32)illiseconds );
h
h
}
// Friendly PlaySound() wrapper for playing wave
files
public static void PlayWave(String filename, Boolean
looped) {
UInt32 flags = sndAsyncFlag | sndFilenameFlag;
if( looped ) flags |= sndLoopFlag;
if( !PlaySound( filename, , flags ) )
{
Int32 err = tWin32Error();
throw new Win32Exception( err );
}
}
// Friendly PlaySound() wrapper for playing wave
files
public static void PlayWave(String filename){
PlayWave( filename, false );
}
// Friendly PlaySound() wrapper for stopping wave
files
public static void StopWave(){
PlayWave( null );
}
// static extern methods for making sound through
interop
[DllImport( "", SetLastError = true )]
static extern Boolean MessageBeep(UInt32 beepType);
[DllImport( "", EntryPoint = "Beep",
SetLastError = true)]
static extern Boolean UnmanagedBeep(UInt32 frequency,
UInt32 duration);
[DllImport( "", CharSet = ,
SetLastError = true)]
static extern Boolean PlaySound(String filename,
IntPtr module, UInt32 flags);
// Some private helper values for calling PlaySound
const UInt32 sndAsyncFlag = 0x0001;
h
h
const UInt32 sndLoopFlag = 0x0008;
const UInt32 sndFilenameFlag = 0x00020000;
private Sound(){}
}
// Enum for message beep types
enum BeepTypes{
Simple = -1,
Ok = 0x00000000,
IconHand = 0x00000010,
IconQuestion = 0x00000020,
IconExclamation = 0x00000030,
IconAsterisk = 0x00000040
}
}
h
h
[DllImport("")]
public static extern long PlaySound(string name,long module,long flag);
[DllImport("")]
private static extern long mciSendString(string lpstrCommand,string lpstrReturnString,long length,long hwndcallback);
private string m_MusicName="";
private void PlayMusic()
{
m_MusicName="""+fo("promptmusicfile")+""";
if(m_==0)
return;
try
{
mciSendString(@"close " +
mciSendString(@"open " +
mciSendString(@"play " +
}
catch
{
}
}
private void StopMusic()
{
try
{
mciSendString(@"close " +
}
catch{}
}
m_MusicName,"
",0,0);
",0,0);
,"
",0,0);
m_MusicName,"
",0,0);
h
m_MusicName,"
m_MusicName
h
播放内存中的WAV文件可以这样:
//API定义
private const int SND_ASYNC = 0x1;
private const int SND_MEMORY = 0x4;
[DllImport("")]
private static extern int sndPlaySoundA(byte[] lpszSoundName, int uFlags);
//将添加入工程并设置为嵌入的资源
//现在是将它读入内存备用
Type t=e();
ly a=ly;
stream=ifestResourceStream(ace+".");
byte[] ba=new byte[];
(ba,0, );
();
//播放缓存
sndPlaySoundA(ba, SND_MEMORY);
h
h
•
用API函数winmm下的PlaySound播放声音:
(一). 说明
一个播放音乐的类,要准备好自己的音乐文件,比如: *.mid/*.wav等
(二).步骤
using System;
using tions;
using entModel;
using pServices;
namespace 象棋游戏音效支持类
{
///
/// 用于播放音乐
///
internal class Helpers
{
[Flags]
public enum PlaySoundFlags : int
{
SND_SYNC = 0x0000, /* play synchronously (default) */ //同步
SND_ASYNC = 0x0001, /* play asynchronously */ //异步
SND_NODEFAULT = 0x0002, /* silence (!default) if sound
not found */
SND_MEMORY = 0x0004, /* pszSound points to a memory file */
SND_LOOP = 0x0008, /* loop the sound until next sndPlaySound */
SND_NOSTOP = 0x0010, /* don't stop any currently playing sound */
SND_NOWAIT = 0x00002000, /* don't wait if the driver is busy */
SND_ALIAS = 0x00010000, /* name is a registry alias */
SND_ALIAS_ID = 0x00110000, /* alias is a predefined ID */
SND_FILENAME = 0x00020000, /* name is file name */
SND_RESOURCE = 0x00040004 /* name is resource name or
atom */
}
[DllImport("winmm")]
public static extern bool PlaySound( string szSound, IntPtr hMod, PlaySoundFlags flags );
h
h
}
public class Sound
{
public static void Play( string strFileName )
{
switch(strFileName)
{
case "start": strFileName=@"....";
break;
h
h
case "back": strFileName=@"...."; break;
case "fall": strFileName=@"...."; break;
case "huiqi": strFileName=@"...."; break;
case "huiqiend": strFileName=@"...."; break;
case "jiangjun": strFileName=@"...."; break;
case "kill": strFileName=@"...."; break;
case "win": strFileName=@"...."; break;
case "move": strFileName=@"...."; break;
case "hold": strFileName=@"...."; break;
case "no": strFileName=@"....";
break;
case "popup": strFileName=@"...."; break;
case "mayfall": strFileName=@"...."; break;
}
//调用PlaySound方法,播放音乐
und(strFileName, , _FILENAME
| _ASYNC); }
}
}
(三).使用
1.添加组件 () . 这个类库 自带的,默认没有添加进来.
方法: 展开项目文件夹,右击引用,添加引用,到Com组件栏,找到添加到项目中.
2.新建一个*.cs文件,把这些代码拷贝进去,全部覆盖即可,并修改上例子中的播放文件名.
就是这样的语句: strFileName=@"...."; //一定要存在这个音乐文件,否则不能播放
3.如果调用这个方法的地方与此类不在同一个命名空间. 要在用的地方打开类的命名空间.
方法: 如这个示例类的命名空间应该这样写: using PlaySound;
最后就可以用了,用法极简单,直接调用此类的方法:
h
h
("move"); //其中参数为音乐文件名(自定义)
相应Blog链接:
/chengking/archive/2005/10/07/
h
h
using System;
using c;
using ;
using ;
using pServices;
namespace MovSysSht
{
internal class CSoundPlay
{
public CSoundPlay()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
[Flags]
public enum PlaySoundFlags : int
{
SND_SYNC = 0x0000, /* play synchronously (default)
*/
SND_ASYNC = 0x0001, /* play asynchronously */
SND_NODEFAULT = 0x0002, /* silence (!default) if
sound not found */
SND_MEMORY = 0x0004, /* pszSound points to a
memory file */
SND_LOOP = 0x0008, /* loop the sound until next
sndPlaySound */
SND_NOSTOP = 0x0010, /* don't stop any currently
playing sound */
SND_NOWAIT = 0x00002000, /* don't wait if the
driver is busy */
SND_ALIAS = 0x00010000, /* name is a registry
alias */
SND_ALIAS_ID = 0x00110000, /* alias is a
predefined ID */
SND_FILENAME = 0x00020000, /* name is file name
*/
SND_RESOURCE = 0x00040004 /* name is resource
name or atom */
}
h
h
[DllImport("")]
public static extern bool PlaySound(string szSound,
IntPtr hMod, PlaySoundFlags flags);
}h
h
public class Sound
{
public static void Play(string strFileName)
{
und(strFileName, ,
_FILENAME |
_ASYNC);
}
}
}
h
h
c#播放mp3控件
C# 播放器空件 的常用方法
//****************************************************************************//
MediaPlay 9
右击工具箱->选择项(I)... -> 显示"选择工具箱项" -> COM组件 -> Windows Media Player
添加
lessVideo = false; //设为false后双击屏幕可以全屏
reen = true; //设播放器全屏播放
= @"mms://192.168.0.102/vod/";
(); //播放
(); //停止
(); //暂停
art = true; //自动播放
= false; //静音
= 100; // 音量 int 0 ~ 100 100 是最大音量
ng();//影片长度
tPosition = 30; //当前的播放位置 double
mInfo("Title");//标题
mInfo("Author");//作者
//*****************************************************************************//
//*****************************************************************************//
MediaPlay 以前版本
h
h
右击工具箱->选择项(I)... -> 显示"选择工具箱项" -> COM组件 -> 浏览(B)... -> C: -> 打开
Windows Media Player 添加
= ng(); //音量
me = @"mms://218.98.101.164/vod/";//文件路径
(); //开始播放
//******************************************************************************//
//****************************************************************************//
右击工具箱->选择项(I)... -> 显示"选择工具箱项" -> COM组件 -> RealPlayer G2 Control 添加
= @"F:3"; //播放路径
yPause(); //Bool 型是否能暂停
se(); //暂停
Pause(); //正在播放的影片暂停播放
y(); //Bool是否能播放
(); //播放
p() //播放是否可以停止
(); //播放停止
ter(true); //按影片原大小播放
lScreen();//播放器全屏播放影片
int place = ition();
();
te*(**lse); //拉伸播放 ter(true); 按影片原始大小播放
();
ition(place);
nResL = ition(); //获得当前影片 的播放进度
h
h
= le(); //获得影片的标题
= "当前的带宽: " + dwidthCurrent() / 1024 + "KB";//当前影片的当前的带宽
= "连接的带宽: " + nectionBandwidth() / 1024 + "KB"; //当前的连接的带宽
h
h
怎么获取mp3的头文件信息
比如歌曲名,歌手等
呵呵,我以前回答过这个问题,可以看看以前我的得分贴:!
/Expert/topic/2349/?temp=.1675074
static void Main(string[] args)
{
byte[] b = new byte[128];
string sTitle;
string sSinger;
string sAlbum;
string sYear;
string sComm;
FileStream fs = new FileStream(@"d:3", );
(-128, );
(b, 0, 128);
bool isSet=false;
String sFlag = ing(b, 0, 3);
if (eTo("TAG")==0)
{
ine ("Tag is setted!");
isSet=true;
}
if (isSet)
{
//get title of song;
sTitle = ing (b,3,30);
ine ("Title:" + sTitle);
//get singer;
sSinger = ing (b,33,30);
ine ("Singer:" + sSinger);
//get album;
sAlbum = ing (b,63,30);
ine ("Album:" + sAlbum);
//get Year of publish;
sYear= ing (b,93,4);
ine ("Year:" + sYear);
//get Comment;
sComm= ing (b,97,30);
ine ("Comment:" + sComm);
}
ine("Any key to exit!");
h
h
();
}
上面是取得v1的方法
h
h
C#中用API实现MP3等音频文件的播放类
C#没有提供播放MP3等音频文件的类,要编写播放MP3等音频文件程序,必须使用第三方控件或类。本文使用API函数mciSendString,编写一个播放MP3等音频文件的类。
具体源码如下:
一、使用API函数mciSendString构成的媒体播放类。
using System;
using pServices;
using ;
using ;
namespace clsMCIPlay
{
///
/// clsMci 的摘要说明。
///
public class clsMCI
{
public clsMCI()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
//定义API函数使用的字符串变量
[MarshalAs(Str,SizeConst=260)]
private string Name = "" ;
[MarshalAs(Str,SizeConst=128)]
private string durLength = "" ;
[MarshalAs(,SizeConst=128)]
private string TemStr ="";
int ilong;
//定义播放状态枚举变量
public enum State
{
mPlaying = 1,
mPuase = 2,
mStop = 3
};
//结构变量
public struct structMCI
{
public bool bMut;
public int iDur;
h
h
public int iPos;
h
h
public int iVol;
public int iBal;
public string iName;
public State state;
};
public structMCI mc =new structMCI() ;
//取得播放文件属性
public string FileName
{
get
{
return ;
}
set
{
//ASCIIEncoding asc = new ASCIIEncoding();
try
{
TemStr ="";
TemStr = t(127,(" "));
Name = t(260,(" ")) ;
= value;
ilong = rtPathName(,Name, );
Name = GetCurrPath(Name);
//Name = "open " + (34) + Name + (34) + " alias media";
Name = "open " + (34) + Name + (34) + " alias media";
ilong = dString("close all", TemStr, , 0);
ilong = dString( Name, TemStr, , 0);
ilong = dString("set media time format milliseconds", TemStr, , 0);
= ;
}
catch
{
("出错错误!");
}
}
}
//播放
public void play()
{
TemStr = "";
TemStr = t(127,(" "));
dString("play media", TemStr, , 0);
h
h
= ng ;
}
//停止
public void StopT()
{
TemStr = "";
TemStr = t(128,(" "));
ilong = dString("close media", TemStr, 128, 0);
ilong = dString("close all", TemStr, 128, 0);
= ;
}
public void Puase()
{
TemStr = "";
TemStr = t(128,(" "));
ilong = dString("pause media", TemStr, , 0);
= ;
}
private string GetCurrPath(string name)
{
if( <1) return "";
name = ();
name = ing(0,-1);
return name;
}
//总时间
public int Duration
{
get
{
durLength = "";
durLength = t(128,(" ")) ;
dString("status media length", durLength, , 0);
durLength = ();
if(durLength == "") return 0;
return (int)(le(durLength) / 1000f);
}
}
//当前时间
public int CurrentPosition
{
get
{
h
h
h
h
durLength = "";
durLength = t(128,(" ")) ;
dString("status media position", durLength, , 0);
= (int)(le(durLength) / 1000f);
return ;
}
}
}
public class APIClass
{
[DllImport("", CharSet = )]
public static extern int GetShortPathName (
string lpszLongPath,
string shortFile,
int cchBuffer
);
[DllImport("", EntryPoint="mciSendString", CharSet = )]
public static extern int mciSendString (
string lpstrCommand,
string lpstrReturnString,
int uReturnLength,
int hwndCallback
);
}
}
二、用于测试媒体播放类的简单代码:
using System;
using g;
using tions;
using entModel;
using ;
using ;
using pServices;
using ;
using ;
using clsMCIPlay;
namespace MCIPlay
{
///
/// Form1 的摘要说明。
///
public class Form1 :
{
h
h
private iner components;
h
h
private timer1;
private Play;
private Stop;
private Puase;
private PlayFileName;
private Duration;
private CurrentPosition;
private leDialog openFileDialog1;
private BrowserFile;
clsMCI mp = new clsMCI();
public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}
///
/// 清理所有正在使用的资源。
///
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
e();
}
}
e( disposing );
}
#region Windows 窗体设计器生成的代码
///
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
///
private void InitializeComponent()
{
ents = new ner();
= new ();
h
h
leName = new ();
h
h
on = new ();
= new ();
= new ();
tPosition = new ();
1 = new (ents);
leDialog1 = new leDialog();
rFile = new ();
dLayout();
//
// Play
//
on = new (102, 243);
= "Play";
= new (78, 24);
ex = 0;
= "Play";
+= new andler(_Click);
//
// PlayFileName
//
ze = true;
on = new (12, 15);
= "PlayFileName";
= new (0, 17);
ex = 1;
//
// Duration
//
ze = true;
on = new (15, 51);
= "Duration";
= new (0, 17);
ex = 2;
//
// Stop
//
on = new (282, 243);
= "Stop";
= new (81, 24);
ex = 3;
= "Stop";
+= new andler(_Click);
//
h
h
// Puase
h
h
//
on = new (198, 243);
= "Puase";
= new (72, 24);
ex = 4;
= "Puase";
+= new andler(_Click);
//
// CurrentPosition
//
ze = true;
on = new (15, 87);
= "CurrentPosition";
= new (0, 17);
ex = 5;
//
// timer1
//
d = true;
al = 1000;
+= new andler(1_Tick);
//
// BrowserFile
//
on = new (312, 165);
= "BrowserFile";
= new (87, 24);
ex = 6;
= "SelectFile";
+= new andler(rFile_Click);
//
// Form1
//
aleBaseSize = new (6, 14);
Size = new (433, 287);
(rFile);
(tPosition);
();
();
(on);
(leName);
();
= "Form1";
h
h
= "Form1";
Layout(false);
}
#endregion
///
/// 应用程序的主入口点。
///
[STAThread]
static void Main()
{
(new Form1());
}
//选择MP3文件播放
private void Play_Click(object sender, rgs e)
{
try
{
();
}
catch
{
("出错错误!");
}
}
//暂停播放
private void Puase_Click(object sender, rgs e)
{
try
{
();
}
catch
{
("出错错误!");
}
}
//停止播放
private void Stop_Click(object sender, rgs e)
{
try
{
();
}
h
h
catch
h
h
{
("出错错误!");
}
}
//每秒显示一次播放进度
private void timer1_Tick(object sender, rgs e)
{
= ng();
}
//浏览文件
private void BrowserFile_Click(object sender, rgs e)
{
try
{
= "*.mp3|*.mp3";
me = "";
if(alog() == )
{
me = me ;
= me ;
= ng() ;
}
}
catch
{
("出错错误!");
}
}
}
}
0
0
(请您对文章做出评价)
h
h
C#中利用mediaplayer打造mp3播放器
利用Window Media Player 控件自己做一款小巧的mp3播放器来听音乐 ,是不是很享受呢?今天刚写出来的,听听mp3感觉还不错哦。 闲话少说,进入正题。
Mp3播放器主要完成下列功能:
1. 添加歌曲,可以添加单个乐曲或者指定文件夹内包括其子文件夹内的所有mp3乐曲到播放列表。
2. 删除指定歌曲或所有歌曲。
3. 播放的控制。包括选择上一首,下一首播放,顺序播放,循环播放和随机播放。循环播放又分单个歌曲的循环播放和所有歌曲的循环播放。
首先建立类player。
public class Player
{
private owsMediaPlayer myPlayer;
private string[] playList;
private int numOfMusic;
private int currentPlay;
public int NumOfMusic
{
get
{
return numOfMusic;
}
}
public yState playstate
{
get
{
return ate;
}
}
public string PlayList(int num)
h
h
{
return playList[num];
h
h
}
public Player(owsMediaPlayer mediaPlayer)
{
myPlayer = mediaPlayer;
playList = new string[1000];
numOfMusic = 0;
}
public void AddFile(string path)
{
if(numOfMusic < 1000)
{
numOfMusic ++;
playList[numOfMusic] = path;
}
}
public void DelFile(int selectNum)
{
for(int i = selectNum; i <= numOfMusic - 1; i++)
{
playList[i] = playList[i + 1];
}
numOfMusic --;
}
public void play(int selectNum)
{
= playList[selectNum];
currentPlay = selectNum;
}
public int NextPlay(int type)
{
/* type = 0 顺序
type = 1 重复播放全部
type = 2 重复播放一首
type = 3 随机播放
*/
h
h
h
h
switch (type)
{
case 0:
currentPlay ++;
if(currentPlay > numOfMusic)return 0;
else return currentPlay;
case 1:
currentPlay ++;
if(currentPlay > numOfMusic) return 1;
else return currentPlay;
case 2:
return currentPlay;
case 3:
Random rdm = new Random(unchecked((int)));
currentPlay = () % numOfMusic;
if(currentPlay == 0) return numOfMusic;
else return currentPlay;
default:
return 0;
}
}
}
Player类中包括一个windowsMediaPlayer对象myPlayer,一个存储播放列表的数组playlist,记录歌曲总数的numOfMusic,以及当前播放的歌曲对应列表中的序号currentplay; 另外有四个方法分别是Play,AddFile,DelFile,以及获得下次播放序号的NextPlay
分功能列出其他主要代码
添加单个歌曲
if(alog() == )
{
string path = me;
FileInfo f = new FileInfo(path);
e(me);
string STRFILE = ng(usic);
for(int i = 1;i<=;i++)STRFILE+=’ ’;
STRFILE += ;
(STRFILE);
}
添加一个文件夹及其所有子文件夹的歌曲
h
h
利用递归函数showfiles实现所有层歌曲都添加到歌曲列表中。
private void showfiles(string path,ListBox listBox1)
{
DirectoryInfo dir = new DirectoryInfo(path);
foreach(FileInfo f in es("*.mp3"))
{
e(me);
}
foreach(DirectoryInfo f in ectories())
{
showfiles(me,listBox1);
}
删除和清空直接调用类Player中的AddFile和DelFile函数
实现播放上一首
if(edIndex >= 0)
{
edIndex --;
if(edIndex <0)edIndex = usic - 1;
(edIndex + 1);
}
下一首
if(edIndex >= 0)
{
edIndex = (edIndex + 1) % usic;
(edIndex + 1);
}
播放的控制
利用Player的NextPlay方法返回的值来选择下一次播放的内容。
同时利用PlayStateChange事件来实现由一曲到下一曲的替换,但是在响应PlayStateChange事件的时候直接改变Player的url无法让它直接播放下一曲,解决方法如下:
private void axWindowsMediaPlayer1_PlayStateChange(object sender,
h
h
AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
h
h
{
if(ate == ediaEnded)
{
();
}
}
private void timer1_Tick(object sender, rgs e)
{
();
int selectnum = 0;
if(d)selectnum = ay(0);
else if (d)selectnum = ay(1);
else if (d)selectnum = ay(2);
else if (d)selectnum = ay(3);
if(selectnum != 0)
{
edIndex = selectnum - 1;
(selectnum);
}
}
满足一首歌曲结束的条件的时候唤醒计时器,计时器100ms内就响应函数timer1_Tick,在这个函数里实现下一首歌曲的选择播放便可以顺利进行.
至此主要功能便完成了!立刻用来听听mp3,自己的东西感觉就是不一样哦!
0
0
(请您对文章做出评价)
h
h
闲得蛋疼,用C#写的一个计算mp3播放时间长度的类,可计算Xing、VBRi、CBR三种格式的mp3长度。
问题写在代码后面
[code=C#]
///
/// 将Mp3转为byte[]
///
/// mp3的路径
///
public byte[] getByte(string FileName)
{
FileStream fs = new FileStream(FileName, ,);
int seekPos = 32();
BinaryReader r = new BinaryReader(fs);
(0, );
byte[] Info = new byte[seekPos];
Info = tes((int));
//return (byte[])EndianFlip(Info);
return Info;
}
public static object EndianFlip(object oObject)
{
string sFieldType;
Type tyObject = e();
FieldInfo[] miMembers;
miMembers = lds();
for (int Looper = erBound(0);
Looper <= erBound(0);
Looper++)
{
sFieldType = miMembers[Looper].me;
if ((e(sFieldType, "16", true) == 0))
{
ushort tmpUShort;
tmpUShort = (ushort)miMembers[Looper].GetValue(oObject);
tmpUShort = (ushort)(((tmpUShort & 0x00ff) < < 8) +
((tmpUShort & 0xff00) >> 8));
miMembers[Looper].SetValue(oObject, tmpUShort);
h
h
}
else
if (e(sFieldType, "32", true) == 0)
{
uint tmpInt;
tmpInt = (uint)miMembers[Looper].GetValue(oObject);
tmpInt = (uint)(((tmpInt & 0x000000ff) < < 24) +
((tmpInt & 0x0000ff00) < < 8) +
((tmpInt & 0x00ff0000) >> 8) +
((tmpInt & 0xff000000) >> 24));
miMembers[Looper].SetValue(oObject, tmpInt);
}
}
return (oObject);
}
///
/// 获取mp3帧头位置
///
/// mp3的byte串
///
public int getframeHeader(byte[] Info)
{
//(bytes[0] < < 8) + bytes[1]
int i = 0;
ushort txt ;
ushort txt2 = 65472;
do
{
txt = 16((Info[i] < < 8) + Info[i + 1]);
i++;
}
while(txt < txt2);
return i-1;
}
///
/// 获取mp3的版本信息
///
/// mp3的byte
/// 帧头位置
///
public string getMPEGVersion(byte[] info,int frameHead)
h
h
{
string strCode = "";
byte[] a = new byte[4];
a[0] = info[frameHead];
a[1] = info[frameHead + 1];
a[2] = info[frameHead + 2];
a[3] = info[frameHead + 4];
StringBuilder sb = new StringBuilder();
foreach (byte i in a)
{
(DtoB((char)i));
}
string str1 = ng();
strCode = ing(11, 2);
string MPEGVersion;
switch (strCode)
{
case "00":
MPEGVersion = "MPEG 2.5";
break;
case "01":
MPEGVersion = "保留";
break;
case "10":
MPEGVersion = "MPEG 2";
break;
default:
MPEGVersion = "MPEG 1";
break;
}
return MPEGVersion;
}
///
/// 获取mp3的版本的二进制代码
///
/// mp3的二进制码
/// 帧头位置
///
public int getMPEGVersionCode(byte[] info, int frameHead)
{
string strCode = "";
byte[] a = new byte[4];
h
h
a[0] = info[frameHead];
a[1] = info[frameHead + 1];
a[2] = info[frameHead + 2];
a[3] = info[frameHead + 3];
StringBuilder sb = new StringBuilder();
foreach (byte i in a)
{
(DtoB((char)i));
}
string str1 = ng();
strCode = ing(11, 2);
int Code = 32(strCode);
return Code;
}
///
/// 获取MPEG的Layer
///
/// mp3的byte串
/// 帧头位置
///
public string getMPEGLayer(byte[] info, int frameHead)
{
string strCode = "";
byte[] a = new byte[4];
a[0] = info[frameHead];
a[1] = info[frameHead + 1];
a[2] = info[frameHead + 2];
a[3] = info[frameHead + 3];
StringBuilder sb = new StringBuilder();
foreach (byte i in a)
{
(DtoB((char)i));
}
string str1 = ng();
strCode = ing(13, 2);
string MPEGLayer = "";
switch (strCode)
{
case "00":
MPEGLayer = "保留";
break;
case "01":
MPEGLayer = "Layer III";
h
h
break;
case "10":
MPEGLayer = "Layer II";
break;
default:
MPEGLayer = "Layer I";
break;
}
return MPEGLayer;
}
///
/// 获取MPEG的Layer的二进制代码
///
/// mp3的二进制码
/// 帧头位置
///
public string getMPEGLayerCode(byte[] info, int frameHead)
{
string strCode = "";
byte[] a = new byte[4];
a[0] = info[frameHead];
a[1] = info[frameHead + 1];
a[2] = info[frameHead + 2];
a[3] = info[frameHead + 3];
StringBuilder sb = new StringBuilder();
foreach (byte i in a)
{
(DtoB((char)i));
}
string str1 = ng();
strCode = ing(13, 2);
return strCode;
}
欢迎您的下载,资料仅供参考!
h


发布评论