MediaPlayerExample.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. using System;
  2. using System.IO;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using UnityEngine.Serialization;
  6. using Agora.Rtc;
  7. using Agora.Util;
  8. using Logger = Agora.Util.Logger;
  9. namespace Agora_RTC_Plugin.API_Example.Examples.Advanced.MediaPlayer
  10. {
  11. public class MediaPlayerExample : MonoBehaviour
  12. {
  13. [FormerlySerializedAs("appIdInput")]
  14. [SerializeField]
  15. private AppIdInput _appIdInput;
  16. [Header("_____________Basic Configuration_____________")]
  17. [FormerlySerializedAs("APP_ID")]
  18. [SerializeField]
  19. private string _appID = "";
  20. [FormerlySerializedAs("TOKEN")]
  21. [SerializeField]
  22. private string _token = "";
  23. [FormerlySerializedAs("CHANNEL_NAME")]
  24. [SerializeField]
  25. private string _channelName = "";
  26. public Text LogText;
  27. internal Logger Log;
  28. internal IRtcEngine RtcEngine = null;
  29. internal IMediaPlayer MediaPlayer = null;
  30. private const string MPK_URL = "https://agoracdn.s3.us-west-1.amazonaws.com/videos/Agora.io-Interactions.mp4";
  31. private const string PRELOAD_URL = "https://agoracdn.s3.us-west-1.amazonaws.com/videos/Agora+Quality+Comparison+Jellyfish.mp4";
  32. private Button _button1;
  33. private Button _button2;
  34. private Button _button3;
  35. private Button _button4;
  36. private Button _button5;
  37. private Button _button6;
  38. private Button _button7;
  39. private Button _button8;
  40. private Button _button9;
  41. private Toggle _urlToggle;
  42. private Toggle _loopToggle;
  43. private InputField _inputField;
  44. // Use this for initialization
  45. private void Start()
  46. {
  47. LoadAssetData();
  48. if (CheckAppId())
  49. {
  50. SetUpUI();
  51. EnableUI(false);
  52. InitEngine();
  53. InitMediaPlayer();
  54. JoinChannelWithMPK();
  55. }
  56. }
  57. // Update is called once per frame
  58. private void Update()
  59. {
  60. PermissionHelper.RequestMicrophontPermission();
  61. PermissionHelper.RequestCameraPermission();
  62. }
  63. private void SetUpUI()
  64. {
  65. _button1 = GameObject.Find("Button1").GetComponent<Button>();
  66. _button1.onClick.AddListener(OnPlayButtonPress);
  67. _button2 = GameObject.Find("Button2").GetComponent<Button>();
  68. _button2.onClick.AddListener(OnStopButtonPress);
  69. _button3 = GameObject.Find("Button3").GetComponent<Button>();
  70. _button3.onClick.AddListener(OnPauseButtonPress);
  71. _button4 = GameObject.Find("Button4").GetComponent<Button>();
  72. _button4.onClick.AddListener(OnResumeButtonPress);
  73. _button5 = GameObject.Find("Button5").GetComponent<Button>();
  74. _button5.onClick.AddListener(OnOpenButtonPress);
  75. _button6 = GameObject.Find("Button6").GetComponent<Button>();
  76. _button6.onClick.AddListener(OnPreloadSrcButtonClick);
  77. _button7 = GameObject.Find("Button7").GetComponent<Button>();
  78. _button7.onClick.AddListener(OnPlayPreloadButtonClick);
  79. _button8 = GameObject.Find("Button8").GetComponent<Button>();
  80. _button8.onClick.AddListener(OnStartPublishButtonClick);
  81. _button8.gameObject.SetActive(false);
  82. _button9 = GameObject.Find("Button9").GetComponent<Button>();
  83. _button9.onClick.AddListener(OnStopPublishButtonClick);
  84. _urlToggle = GameObject.Find("UrlToggle").GetComponent<Toggle>();
  85. _loopToggle = GameObject.Find("LoopToggle").GetComponent<Toggle>();
  86. _inputField = GameObject.Find("InputField").GetComponent<InputField>();
  87. }
  88. public void EnableUI(bool val)
  89. {
  90. var obj = this.transform.Find("Button1").gameObject;
  91. obj.SetActive(val);
  92. obj = this.transform.Find("Button2").gameObject;
  93. obj.SetActive(val);
  94. obj = this.transform.Find("Button3").gameObject;
  95. obj.SetActive(val);
  96. obj = this.transform.Find("Button4").gameObject;
  97. obj.SetActive(val);
  98. }
  99. private bool CheckAppId()
  100. {
  101. Log = new Logger(LogText);
  102. return Log.DebugAssert(_appID.Length > 10, "Please fill in your appId in API-Example/profile/appIdInput.asset");
  103. }
  104. //Show data in AgoraBasicProfile
  105. [ContextMenu("ShowAgoraBasicProfileData")]
  106. private void LoadAssetData()
  107. {
  108. if (_appIdInput == null) return;
  109. _appID = _appIdInput.appID;
  110. _token = _appIdInput.token;
  111. _channelName = _appIdInput.channelName;
  112. }
  113. private void InitEngine()
  114. {
  115. RtcEngine = Agora.Rtc.RtcEngine.CreateAgoraRtcEngine();
  116. UserEventHandler handler = new UserEventHandler(this);
  117. RtcEngineContext context = new RtcEngineContext(_appID, 0,
  118. CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_LIVE_BROADCASTING,
  119. AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_GAME_STREAMING);
  120. RtcEngine.Initialize(context);
  121. RtcEngine.InitEventHandler(handler);
  122. var logFile = Application.persistentDataPath + "/rtc.log";
  123. RtcEngine.SetLogFile(logFile);
  124. this.Log.UpdateLog("logFile:" + logFile);
  125. }
  126. private void InitMediaPlayer()
  127. {
  128. MediaPlayer = RtcEngine.CreateMediaPlayer();
  129. if (MediaPlayer == null)
  130. {
  131. this.Log.UpdateLog("CreateMediaPlayer failed!");
  132. return;
  133. }
  134. MpkEventHandler handler = new MpkEventHandler(this);
  135. MediaPlayer.InitEventHandler(handler);
  136. this.Log.UpdateLog("playerId id: " + MediaPlayer.GetId());
  137. }
  138. private void JoinChannelWithMPK()
  139. {
  140. RtcEngine.EnableAudio();
  141. RtcEngine.EnableVideo();
  142. RtcEngine.SetClientRole(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  143. ChannelMediaOptions options = new ChannelMediaOptions();
  144. options.autoSubscribeAudio.SetValue(true);
  145. options.autoSubscribeVideo.SetValue(true);
  146. options.publishCustomAudioTrack.SetValue(false);
  147. options.publishCameraTrack.SetValue(false);
  148. options.publishMediaPlayerAudioTrack.SetValue(true);
  149. options.publishMediaPlayerVideoTrack.SetValue(true);
  150. options.publishMediaPlayerId.SetValue(MediaPlayer.GetId());
  151. options.enableAudioRecordingOrPlayout.SetValue(true);
  152. options.clientRoleType.SetValue(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  153. var ret = RtcEngine.JoinChannel(_token, _channelName, 0, options);
  154. this.Log.UpdateLog("RtcEngineController JoinChannel_MPK returns: " + ret);
  155. }
  156. private void OnPlayButtonPress()
  157. {
  158. if (this.IsLoop())
  159. {
  160. MediaPlayer.SetLoopCount(-1);
  161. }
  162. else
  163. {
  164. MediaPlayer.SetLoopCount(0);
  165. }
  166. var ret = MediaPlayer.Play();
  167. this.Log.UpdateLog("Play return" + ret);
  168. this.TestMediaPlayer();
  169. }
  170. private void OnStopButtonPress()
  171. {
  172. var ret = MediaPlayer.Stop();
  173. this.Log.UpdateLog("Stop return" + ret);
  174. }
  175. private void OnPauseButtonPress()
  176. {
  177. var ret = MediaPlayer.Pause();
  178. this.Log.UpdateLog("Pause return" + ret);
  179. }
  180. private void OnResumeButtonPress()
  181. {
  182. var ret = MediaPlayer.Resume();
  183. this.Log.UpdateLog("Resume returns: " + ret);
  184. }
  185. private void OnOpenButtonPress()
  186. {
  187. string path = null;
  188. if (this._urlToggle.isOn)
  189. {
  190. if (this._inputField.text == "")
  191. {
  192. path = MPK_URL;
  193. }
  194. else
  195. {
  196. path = this._inputField.text;
  197. }
  198. }
  199. else
  200. {
  201. #if UNITY_ANDROID && !UNITY_EDITOR
  202. // On Android, the StreamingAssetPath is just accessed by /assets instead of Application.streamingAssetPath
  203. path = "/assets/img/MPK.mov";
  204. #else
  205. path = Path.Combine(Application.streamingAssetsPath, "img/MPK.mov");
  206. #endif
  207. }
  208. this.Log.UpdateLog("Is opening : " + path);
  209. var ret = MediaPlayer.Open(path, 0);
  210. this.Log.UpdateLog("Open returns: " + ret);
  211. }
  212. private void OnOpenWithCustomSource()
  213. {
  214. var ret = MediaPlayer.OpenWithCustomSource(0, new UserPlayerCustomDataProvider(this));
  215. this.Log.UpdateLog("OpenWithCustomSource" + ret);
  216. }
  217. private void OnPreloadSrcButtonClick()
  218. {
  219. var nRet = MediaPlayer.PreloadSrc(PRELOAD_URL, 0);
  220. this.Log.UpdateLog("PreloadSrc: " + nRet);
  221. }
  222. private void OnPlayPreloadButtonClick()
  223. {
  224. var nRet = MediaPlayer.PlayPreloadedSrc(PRELOAD_URL);
  225. this.Log.UpdateLog("PlayPreloadedSrc: " + nRet);
  226. }
  227. private void TestMediaPlayer()
  228. {
  229. long duration = 0;
  230. var ret = MediaPlayer.GetDuration(ref duration);
  231. Debug.Log("_mediaPlayer.GetDuration returns: " + ret + "duration: " + duration);
  232. long pos = 0;
  233. ret = MediaPlayer.GetPlayPosition(ref pos);
  234. Debug.Log("_mediaPlayer.GetPlayPosition returns: " + ret + "position: " + pos);
  235. Debug.Log("_mediaPlayer.GetState:" + MediaPlayer.GetState());
  236. bool mute = true;
  237. ret = MediaPlayer.GetMute(ref mute);
  238. Debug.Log("_mediaPlayer.GetMute returns: " + ret + "mute: " + mute);
  239. int volume = 0;
  240. ret = MediaPlayer.GetPlayoutVolume(ref volume);
  241. Debug.Log("_mediaPlayer.GetPlayoutVolume returns: " + ret + "volume: " + volume);
  242. Debug.Log("SDK Version:" + MediaPlayer.GetPlayerSdkVersion());
  243. Debug.Log("GetPlaySrc:" + MediaPlayer.GetPlaySrc());
  244. }
  245. private void OnStartPublishButtonClick()
  246. {
  247. var options = new ChannelMediaOptions();
  248. options.publishMediaPlayerVideoTrack.SetValue(true);
  249. options.publishMediaPlayerAudioTrack.SetValue(true);
  250. options.publishMediaPlayerId.SetValue(MediaPlayer.GetId());
  251. var nRet = RtcEngine.UpdateChannelMediaOptions(options);
  252. this.Log.UpdateLog("UpdateChannelMediaOptions: " + nRet);
  253. _button8.gameObject.SetActive(false);
  254. _button9.gameObject.SetActive(true);
  255. }
  256. private void OnStopPublishButtonClick()
  257. {
  258. var options = new ChannelMediaOptions();
  259. options.publishMediaPlayerVideoTrack.SetValue(false);
  260. options.publishMediaPlayerAudioTrack.SetValue(false);
  261. options.publishMediaPlayerId.SetValue(MediaPlayer.GetId());
  262. options.publishCameraTrack.SetValue(false);
  263. var nRet = RtcEngine.UpdateChannelMediaOptions(options);
  264. this.Log.UpdateLog("UpdateChannelMediaOptions: " + nRet);
  265. _button8.gameObject.SetActive(true);
  266. _button9.gameObject.SetActive(false);
  267. }
  268. private void OnDestroy()
  269. {
  270. Debug.Log("OnDestroy");
  271. if (RtcEngine == null) return;
  272. if (MediaPlayer != null)
  273. RtcEngine.DestroyMediaPlayer(MediaPlayer);
  274. RtcEngine.InitEventHandler(null);
  275. RtcEngine.LeaveChannel();
  276. RtcEngine.Dispose();
  277. RtcEngine = null;
  278. }
  279. internal string GetChannelName()
  280. {
  281. return _channelName;
  282. }
  283. internal bool IsLoop()
  284. {
  285. return this._loopToggle.isOn;
  286. }
  287. #region -- Video Render UI Logic ---
  288. internal static void MakeVideoView(uint uid, string channelId = "", VIDEO_SOURCE_TYPE videoSourceType = VIDEO_SOURCE_TYPE.VIDEO_SOURCE_CAMERA)
  289. {
  290. var go = GameObject.Find(uid.ToString());
  291. if (!ReferenceEquals(go, null))
  292. {
  293. return; // reuse
  294. }
  295. // create a GameObject and assign to this new user
  296. var videoSurface = MakeImageSurface(uid.ToString());
  297. if (ReferenceEquals(videoSurface, null)) return;
  298. // configure videoSurface
  299. videoSurface.SetForUser(uid, channelId, videoSourceType);
  300. videoSurface.SetEnable(true);
  301. videoSurface.OnTextureSizeModify += (int width, int height) =>
  302. {
  303. float scale = (float)height / (float)width;
  304. videoSurface.transform.localScale = new Vector3(-5, 5 * scale, 1);
  305. Debug.Log("OnTextureSizeModify: " + width + " " + height);
  306. };
  307. }
  308. // VIDEO TYPE 1: 3D Object
  309. private VideoSurface MakePlaneSurface(string goName)
  310. {
  311. var go = GameObject.CreatePrimitive(PrimitiveType.Plane);
  312. if (go == null)
  313. {
  314. return null;
  315. }
  316. go.name = goName;
  317. // set up transform
  318. go.transform.Rotate(-90.0f, 0.0f, 0.0f);
  319. go.transform.position = Vector3.zero;
  320. go.transform.localScale = new Vector3(1.0f, 1.333f, 0.5f);
  321. // configure videoSurface
  322. var videoSurface = go.AddComponent<VideoSurface>();
  323. return videoSurface;
  324. }
  325. // Video TYPE 2: RawImage
  326. private static VideoSurface MakeImageSurface(string goName)
  327. {
  328. GameObject go = new GameObject();
  329. if (go == null)
  330. {
  331. return null;
  332. }
  333. go.name = goName;
  334. // to be renderered onto
  335. go.AddComponent<RawImage>();
  336. // make the object draggable
  337. go.AddComponent<UIElementDrag>();
  338. var canvas = GameObject.Find("VideoCanvas");
  339. if (canvas != null)
  340. {
  341. go.transform.parent = canvas.transform;
  342. Debug.Log("add video view");
  343. }
  344. else
  345. {
  346. Debug.Log("Canvas is null video view");
  347. }
  348. // set up transform
  349. go.transform.Rotate(0f, 0.0f, 180.0f);
  350. go.transform.localPosition = Vector3.zero;
  351. go.transform.localScale = new Vector3(4.5f, 3f, 1f);
  352. // configure videoSurface
  353. var videoSurface = go.AddComponent<VideoSurface>();
  354. return videoSurface;
  355. }
  356. internal static void DestroyVideoView(uint uid)
  357. {
  358. var go = GameObject.Find(uid.ToString());
  359. if (!ReferenceEquals(go, null))
  360. {
  361. Destroy(go);
  362. }
  363. }
  364. #endregion
  365. }
  366. #region -- Agora Event ---
  367. internal class MpkEventHandler : IMediaPlayerSourceObserver
  368. {
  369. private readonly MediaPlayerExample _sample;
  370. internal MpkEventHandler(MediaPlayerExample sample)
  371. {
  372. _sample = sample;
  373. }
  374. public override void OnPlayerSourceStateChanged(MEDIA_PLAYER_STATE state, MEDIA_PLAYER_ERROR ec)
  375. {
  376. _sample.Log.UpdateLog(string.Format(
  377. "OnPlayerSourceStateChanged state: {0}, ec: {1}, playId: {2}", state, ec, _sample.MediaPlayer.GetId()));
  378. Debug.Log("OnPlayerSourceStateChanged");
  379. if (state == MEDIA_PLAYER_STATE.PLAYER_STATE_OPEN_COMPLETED)
  380. {
  381. MediaPlayerExample.MakeVideoView((uint)_sample.MediaPlayer.GetId(), "", VIDEO_SOURCE_TYPE.VIDEO_SOURCE_MEDIA_PLAYER);
  382. _sample.EnableUI(true);
  383. _sample.Log.UpdateLog("Open Complete. Click start to play media");
  384. }
  385. else if (state == MEDIA_PLAYER_STATE.PLAYER_STATE_STOPPED)
  386. {
  387. MediaPlayerExample.DestroyVideoView((uint)_sample.MediaPlayer.GetId());
  388. _sample.EnableUI(false);
  389. }
  390. }
  391. public override void OnPlayerEvent(MEDIA_PLAYER_EVENT @event, Int64 elapsedTime, string message)
  392. {
  393. _sample.Log.UpdateLog(string.Format("OnPlayerEvent state: {0}", @event));
  394. }
  395. public override void OnPreloadEvent(string src, PLAYER_PRELOAD_EVENT @event)
  396. {
  397. _sample.Log.UpdateLog(string.Format("OnPreloadEvent src: {0}, @event: {1}", src, @event));
  398. }
  399. }
  400. internal class UserEventHandler : IRtcEngineEventHandler
  401. {
  402. private readonly MediaPlayerExample _sample;
  403. internal UserEventHandler(MediaPlayerExample sample)
  404. {
  405. _sample = sample;
  406. }
  407. public override void OnError(int err, string msg)
  408. {
  409. _sample.Log.UpdateLog(string.Format("OnError err: {0}, msg: {1}", err, msg));
  410. }
  411. public override void OnJoinChannelSuccess(RtcConnection connection, int elapsed)
  412. {
  413. int build = 0;
  414. _sample.Log.UpdateLog(string.Format("sdk version: ${0}",
  415. _sample.RtcEngine.GetVersion(ref build)));
  416. _sample.Log.UpdateLog(
  417. string.Format("OnJoinChannelSuccess channelName: {0}, uid: {1}, elapsed: {2}",
  418. connection.channelId, connection.localUid, elapsed));
  419. }
  420. public override void OnRejoinChannelSuccess(RtcConnection connection, int elapsed)
  421. {
  422. _sample.Log.UpdateLog("OnRejoinChannelSuccess");
  423. }
  424. public override void OnLeaveChannel(RtcConnection connection, RtcStats stats)
  425. {
  426. _sample.Log.UpdateLog("OnLeaveChannel");
  427. MediaPlayerExample.DestroyVideoView(0);
  428. }
  429. public override void OnClientRoleChanged(RtcConnection connection, CLIENT_ROLE_TYPE oldRole,
  430. CLIENT_ROLE_TYPE newRole)
  431. {
  432. _sample.Log.UpdateLog("OnClientRoleChanged");
  433. }
  434. public override void OnUserJoined(RtcConnection connection, uint uid, int elapsed)
  435. {
  436. _sample.Log.UpdateLog(string.Format("OnUserJoined uid: ${0} elapsed: ${1}", uid, elapsed));
  437. }
  438. public override void OnUserOffline(RtcConnection connection, uint uid, USER_OFFLINE_REASON_TYPE reason)
  439. {
  440. _sample.Log.UpdateLog(string.Format("OnUserOffLine uid: ${0}, reason: ${1}", uid,
  441. (int)reason));
  442. MediaPlayerExample.DestroyVideoView(uid);
  443. }
  444. }
  445. internal class UserPlayerCustomDataProvider : IMediaPlayerCustomDataProvider
  446. {
  447. MediaPlayerExample _sample;
  448. internal UserPlayerCustomDataProvider(MediaPlayerExample sample)
  449. {
  450. _sample = sample;
  451. }
  452. public override Int64 OnSeek(Int64 offset, int whence)
  453. {
  454. Debug.Log("UserPlayerCustomDataProvider OnSeek");
  455. return 0;
  456. }
  457. public override int OnReadData(IntPtr bufferPtr, int bufferSize)
  458. {
  459. Debug.Log("UserPlayerCustomDataProvider OnReadData");
  460. return 0;
  461. }
  462. }
  463. #endregion
  464. }