2020年10月11日 星期日

for xamarin android : how to play sound file (mp3)

 1.檔案一定是要mp3格式(wav檔不行)

2.檔案請放在「Resources」之下,本例為了跟其他資源區分,放在Resources/raw之下,

(有a1.mp3,a2.mp3....)

3.play sound的語法
A.用MediaPlayer:

var  player =MediaPlayer.Create(ApplicationContext,Resource.Raw.a1);
  player.Start();

B.用RingToneManager:

var uriString="android.resource://" + your_package_name + "/" +Resource.Raw.a1;

var uri=Android.Net.Uri.Parse(uriString);

Ringtone r = RingtoneManager.GetRingtone(ApplicationContext, uri);
r.Play();

----------------------------------------------------

以上,大家加油了!!

2020年10月1日 星期四

xamarin: enable & receive UDP broadcast (Android 11 嘛會通哦)

 AndroidManifest.xml

----------------------------------

...

...

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />

-----------------------------------

in android app Activity c# :

---------------------------------

          var wifiManager = (WifiManager)GetSystemService(Context.WifiService);

            MulticastLock mLock = wifiManager.CreateMulticastLock("lock");

            mLock.Acquire();

            using (var udpClient = new UdpClient(你要聆聽的port number)) {

                var asyncResult = udpClient.BeginReceive(null, null);

                var timeToWait = TimeSpan.FromSeconds(30);//30秒,超過就結束

                asyncResult.AsyncWaitHandle.WaitOne(timeToWait);

                if (asyncResult.IsCompleted) {

                    IPEndPoint remoteEP = null;

                    byte[] receivedData = udpClient.EndReceive(asyncResult, ref remoteEP);

                    string msg = System.Text.Encoding.UTF8.GetString(receivedData);

                    Console.WriteLine($"get end point message:{msg}");

                    mLock.Release();

                } else {

                    mLock.Release(); 

                    Console.WriteLine("UDP failed!!!!!!");

                }

            }

--------------------------------

參考 : 這裡

以上,希望對你有幫助