播放嵌入资源的声音文件

 

摘要:本文阐述了在Windows Mobile中如何播放潜入资源的声音文件
%QV/j |(q7j'ry7M0
KeywordsITPUB个人空间 xh3KhBO? Ar
PlaySound, Windows Mobile, Embedded Resources, p/invoke

要在Windows Mobile上播放嵌入资源(Embedded Resource)的声音文件,该怎么办呢?显然是要用到反射的,我查了一下MSDN,还好GetManifestResourceStream对移动设备是可用的。

首先我们需要一个类,通过P/invoke来帮助我们实现播放声音的功能:

   [Flags]
s+d ql/Qm'p0     
enum  SoundFlagsITPUB个人空间bO&F bbQ
    
{
2~ji]/S;Uq0         Alias 
=   0x00010000 ,ITPUB个人空间.?+S1^6} DYS:fs
        Filename 
=   0x00020000 ,ITPUB个人空间 Gj8ks3C}9XF4m
        Synchronous 
=   0x00000000 ,
0}+D3r]2Uv0         Asynchronous 
=   0x00000001 ,
w C"xC+s)b/m zf`0         Memory 
=   0x00000004 ,ITPUB个人空间nlD`'p{PG0_
        Loop 
=   0x00000008 ,
*Is$xzg8Z$Jj0         NoStop 
=   0x00000010
t?kwd1G?y0     }
ITPUB个人空间5b0|?,A%s
ITPUB个人空间�}ogN8j5@J]r6`dW
    
class  PlayNativeRef
Qb"OG5^5O9q1fV y!]0     
{ITPUB个人空间@ x)n&C"c'@
        [DllImport(
" CoreDll.DLL " , EntryPoint  =   " PlaySound " , SetLastError  =   true )]ITPUB个人空间/ S/n BA4e@eUj
        
public   extern   static   int  PlaySound( byte [] szSound, IntPtr hMod, SoundFlags flags);
G jS5w#tdsz^0P0     }

1z u6S9o3z"m!] U /0

调用的时候,我们先要将该声音资源从程序集加载到内存中:

 MemoryStream ms  = (MemoryStream) Assembly.GetExecutingAssembly().GetManifestResourceStream( " PlayEmbeddedAudio.Resources.yuyinlangdu.wav " );ITPUB个人空间7HZ?6]*K]!D8Z
Tips 这里的资源名字,一定不要弄错,如果你不确信的话,可以通过GetManifestResourceNames方法来查看资源的名称。

然后,我们就可以调用PlaySound方法来播放了:

                PlayNativeRef.PlaySound(ITPUB个人空间4fQ3Bdx6b
                     ms.GetBuffer(),
'P&z b,Nu:d&D0                      IntPtr.Zero,
;BRrC$M N0                      SoundFlags.Synchronous 
|  SoundFlags.Memory);   
*GZ-_m3sj"HC9m"r0


S$~:xc#M"yV:C;KD i0
注意这里的SoundFlag要记得把Memory加上,表示第一个参数是指向内存中的声音文件镜像。播放的时候从内存中加载资源。

不过有一点要注意的,嵌入的声音文件不宜太多,否则会让程序集变得很庞大。

代码 在这里下载

原文地址:https://www.cnblogs.com/xyzlmn/p/3168453.html