Created
January 3, 2023 17:13
-
-
Save bbenetskyy/920ea1bb3ad8842637423fff5a53a44a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using AVFoundation; | |
using Foundation; | |
using TheLordOfTheRings.Services;//used for injecting ILogger | |
namespace TheLordOfTheRings.MAUI.Services; | |
public partial class SoundService : IDisposable | |
{ | |
private AVPlayer _player; | |
private AVPlayerItem _playerItem; | |
private readonly ILogger _logger; | |
public SoundService(ILogger logger) | |
{ | |
_player = new AVPlayer(); | |
_logger = logger; | |
} | |
public void PlayIosSound(string sound) | |
{ | |
try | |
{ | |
var directory = Path.GetDirectoryName(sound); | |
var filename = Path.GetFileNameWithoutExtension(sound); | |
var extension = Path.GetExtension(sound).Substring(1); | |
var url = NSBundle.MainBundle.GetUrlForResource(filename, extension, directory); | |
var asset = AVAsset.FromUrl(url); | |
_playerItem = new AVPlayerItem(asset); | |
_player.ReplaceCurrentItemWithPlayerItem(_playerItem); | |
_player.Play(); | |
} | |
catch (Exception ex) | |
{ | |
_logger.LogError(ex); | |
} | |
} | |
void IDisposable.Dispose() | |
{ | |
if (_player != null) | |
{ | |
_player.ReplaceCurrentItemWithPlayerItem(null); | |
_player.Dispose(); | |
_player = null; | |
} | |
if (_playerItem != null) | |
{ | |
_playerItem.Dispose(); | |
_playerItem = null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment