▼.Net Compact Framework 2.0メモ▼
サウンドの再生
サウンドを再生するプログラムを作成する。
サウンドファイルの準備
使用可能なファイル形式はwavとrawとra。
Windows MobileのWindowsフォルダにあるAlerm5.wavとAlerm2.wavを利用。
Alerm5はプログラムに埋め込んで利用。
ソリューションエクスプローラのSoundExを選択し、右クリックし、ポップアップ「追加⇒既存の項目」を選択
ファイルダイアログでAlerm5.wavを選択。
ソリューションエクスプローラのAlerm5.wavを選択し、右クリックし、ポップアップ「プロパティ」を選択。
プロパティのビルドアクションを「埋め込まれたリソース」に変更。
Alerm2.wavは外部ファイルとして読み込んで使うので、そのままでOK。
デザインの編集
SoundForm
プロパティ 値 Text SoundEx MinimizeBox false FormFactor Windows Mobile 6 Professional VGA
Button - btnResSound
プロパティ 値 Text リソースサウンドの再生 Location 20,40 イベント メソッド Click btnResDound_Click
Button - btnFileSound
プロパティ 値 Text ファイルサウンドの再生 Location 20,100 イベント メソッド Click btnFileSound_Click
ソースコードの編集
Sound.cs using System; using System.IO; using System.Runtime.InteropServices; //サウンドライブラリ public class Sound { private byte[] soundBytes; private string fileName; //フラグ private enum Flags { SND_SYNC = 0x0000, SND_ASYNC = 0x0001, SND_NODEFAULT = 0x0002, SND_MEMORY = 0x0004, SND_LOOP = 0x0008, SND_NOSTOP = 0x0010, SND_NOWAIT = 0x00002000, SND_ALIAS = 0x00010000, SND_ALIAS_ID = 0x00110000, SND_FILENAME = 0x00020000, SND_RESOURCE = 0x00040004 } [DllImport("CoreDll.DLL", EntryPoint = "PlaySound", SetLastError = true)] private extern static int WCE_PlaySound(string szSound, IntPtr hMod, int flags); [DllImport("CoreDll.DLL", EntryPoint = "PlaySound", SetLastError = true)] private extern static int WCE_PlaySoundBytes(byte[] szSound, IntPtr hMod, int flags); //コンストラクタ public Sound(string fileName) { this.fileName=fileName; } //コンストラクタ public Sound(Stream stream) { soundBytes=new byte[stream.Length]; stream.Read(soundBytes,0,(int)stream.Length); } //サウンドの再生 public void Play() { if (fileName!=null) { WCE_PlaySound(fileName,IntPtr.Zero,(int)(Flags.SND_ASYNC|Flags.SND_FILENAME)); } else { WCE_PlaySoundBytes(soundBytes,IntPtr.Zero,(int)(Flags.SND_ASYNC|Flags.SND_MEMORY)); } } }
SoundForm.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Reflection; using System.Text; using System.Windows.Forms; namespace SoundEx { public partial class SoundForm : Form { //コンストラクタ public SoundForm() { InitializeComponent(); } //リソースサウンドの再生 private void btnResSound_Click(object sender, EventArgs e) { Sound sound=new Sound(Assembly.GetExecutingAssembly(). GetManifestResourceStream("SoundEx.Alarm5.wav")); sound.Play(); } //ファイルサウンドの再生 private void btnFileSound_Click(object sender, EventArgs e) { try { Sound sound=new Sound("Windows\\Alarm2.wav"); sound.Play(); } catch (Exception exc) { MessageBox.Show(exc.ToString(),"エラー"); } } } }