Skip to content

Commit

Permalink
Bug Fixes.
Browse files Browse the repository at this point in the history
- Fixed issues with seeking
- Fixed #75
- Fixed #73
- Testing more of #74
  • Loading branch information
YBTopaz8 committed Oct 3, 2024
1 parent 33c867a commit a688ac6
Show file tree
Hide file tree
Showing 20 changed files with 294 additions and 278 deletions.
53 changes: 38 additions & 15 deletions Dimmer/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ public App(INativeAudioService audioService)
#elif ANDROID
MainPage = new AppShellMobile();
#endif

}

private void CurrentDomain_FirstChanceException(object? sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine($"********** UNHANDLED EXCEPTION! Details: {e.Exception} | {e.Exception.InnerException?.Message} | {e.Exception.Source} " +

Debug.WriteLine($"********** UNHANDLED EXCEPTION! Details: {e.Exception} | {e.Exception.InnerException?.Message} | {e.Exception.Source} " +
$"| {e.Exception.StackTrace} | {e.Exception.TargetSite}");
#endif

LogException(e.Exception);
}
public Window win;
Expand All @@ -32,12 +32,14 @@ protected override Window CreateWindow(IActivationState activationState)
win.MinimumWidth = 1200;
win.Height = 900;
win.Width = 1200;

win.Title = "Dimmer v0.0.4";

return win;

}

private static readonly object _logLock = new object();
private void LogException(Exception ex)
{
try
Expand All @@ -53,17 +55,38 @@ private void LogException(Exception ex)

string filePath = Path.Combine(directoryPath, "crashlog.txt");

string logContent = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}]\nMsg:{ex.Message}\n StackTrack:{ex.StackTrace}\n";
string logContent = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}]\nMsg:{ex.Message}\nStackTrace:{ex.StackTrace}\n\n";

// Retry mechanism for file writing
bool success = false;
int retries = 3;
int delay = 500; // Delay between retries in milliseconds

lock (_logLock)
{
while (retries-- > 0 && !success)
{
try
{
File.AppendAllText(filePath, logContent);
success = true; // Write successful
}
catch (IOException ioEx) when (retries > 0)
{
System.Diagnostics.Debug.WriteLine($"Failed to log, retrying... ({ioEx.Message})");
System.Threading.Thread.Sleep(delay); // Wait and retry
}
}

File.AppendAllText(filePath, logContent);
if (!success)
{
System.Diagnostics.Debug.WriteLine("Failed to log exception after multiple attempts.");
}
}
}
catch (Exception loggingEx)
{
// Optionally, handle exceptions that occur during logging
// For example, you might want to notify the user or log to an alternative location
// However, avoid throwing exceptions from a logging method to prevent potential infinite loops

Debug.WriteLine($"Failed to log exception: {loggingEx}");
System.Diagnostics.Debug.WriteLine($"Failed to log exception: {loggingEx}");
}
}

Expand All @@ -74,6 +97,6 @@ public override void CloseWindow(Window window)

protected async override void OnSleep()
{

}
}
6 changes: 1 addition & 5 deletions Dimmer/AppShell.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@


using Dimmer_MAUI.UtilitiesServices;

namespace Dimmer_MAUI;
namespace Dimmer_MAUI;

public partial class AppShell : Shell
{
Expand Down
30 changes: 15 additions & 15 deletions Dimmer/CustomPopUpViews/SingleLyricsPreviewPopUp.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@
CanBeDismissedByTappingOutsideOfPopup="False">

<Border StrokeThickness="0" StrokeShape="RoundRectangle, 25"
Stroke="Transparent"
WidthRequest="500" HeightRequest="{OnPlatform WinUI=650, Android=450}"
BackgroundColor="Transparent"
Margin="5"
Padding="10">
<Grid BackgroundColor="Black" Padding="10"
RowDefinitions="*,Auto,50">
Stroke="Transparent"
WidthRequest="500" HeightRequest="{OnPlatform WinUI=450, Android=450}"
BackgroundColor="Black"
Margin="5"
Padding="10">
<Grid BackgroundColor="Transparent" Padding="10"
RowDefinitions="30,Auto,50">
<VerticalStackLayout HorizontalOptions="Center"
Grid.Row="0">
Grid.Row="0">
<HorizontalStackLayout HorizontalOptions="Center">
<Label Text="Artist name" x:Name="ArtistNameLabel" FontSize="23" FontAttributes="Bold"/>
<Label Text=" - " FontSize="23" FontAttributes="Bold"/>
Expand All @@ -30,16 +30,16 @@
</VerticalStackLayout>

<ScrollView Grid.Row="1" HeightRequest="330">
<Label Text="Lyrics" x:Name="LyricsView"
VerticalOptions="Start" HorizontalTextAlignment="Start"
Padding="10"/>
<Label Text="Lyrics" x:Name="LyricsView" LineBreakMode="WordWrap"
VerticalOptions="Start" HorizontalTextAlignment="Start"
Padding="10"/>
</ScrollView>

<HorizontalStackLayout HorizontalOptions="End"
Grid.Row="2">
Grid.Row="2">
<Button Text="Cancel" BackgroundColor="Transparent"
TextColor="Red"
Clicked="CloseButton_Clicked"/>
TextColor="Red"
Clicked="CloseButton_Clicked"/>
<Button Text="Save" Clicked="OkButton_Clicked"/>
</HorizontalStackLayout>
</Grid>
Expand Down
4 changes: 1 addition & 3 deletions Dimmer/DataAccess/Services/SongsManagementService.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System.Diagnostics;

namespace Dimmer_MAUI.DataAccess.Services;
namespace Dimmer_MAUI.DataAccess.Services;

public class SongsManagementService : ISongsManagementService, IDisposable
{
Expand Down
4 changes: 2 additions & 2 deletions Dimmer/MAudioLib/INativeAudioService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ public interface INativeAudioService
public static INativeAudioService Current;
void InitializeAsync(string audioURI);
Task InitializeAsync(MediaPlay media);
Task PlayAsync(bool IsFromUser=false);
Task PlayAsync(double position = 0, bool IsFromUser = false);

Task PauseAsync();
///<Summary>
Expand All @@ -20,7 +20,7 @@ public interface INativeAudioService
///<Summary>
/// Gets the current position of audio playback in seconds.
///</Summary>
double CurrentPosition { get; set; }
double CurrentPosition { get; }
///<Summary>
/// Gets the length of audio in seconds.
///</Summary>
Expand Down
15 changes: 5 additions & 10 deletions Dimmer/Platforms/Android/MAudioLib/MediaPlayerService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
using Android.Graphics;
using Activity = Android.App.Activity;
using Android.Content.PM;
using System.Diagnostics;

namespace Dimmer_MAUI.Platforms.Android.MAudioLib;

Expand Down Expand Up @@ -281,7 +280,7 @@ public object Cover
{
get
{
cover ??= BitmapFactory.DecodeResource(Resources, Resource.Drawable.abc_btn_check_material); //TODO player_play
cover = null;
return cover;
}
set
Expand All @@ -295,11 +294,8 @@ public object Cover
/// <summary>
/// Intializes the player.
/// </summary>
public int currentPositionInMs= 0;
public async Task Play(int position=0)
public async Task Play(int position = 0)
{
var pos = (int)IPlatformApplication.Current.Services.GetService<HomePageVM>().CurrentPositionInSeconds * 100;
currentPositionInMs = position;
Console.WriteLine("Step 6 Play method from mediaplayerservice");
if (mediaPlayer != null && MediaPlayerState == PlaybackStateCode.Paused)
{
Expand All @@ -316,6 +312,7 @@ public async Task Play(int position=0)
return;
}


if (mediaPlayer == null)
{
Console.WriteLine("Media Player is null");
Expand Down Expand Up @@ -468,10 +465,8 @@ public async Task Seek(int position = 0, PlaybackStateCode playbackStateCode = P
{
await Task.Run(() =>
{

var pos = (int)IPlatformApplication.Current.Services.GetService<HomePageVM>().CurrentPositionInSeconds * 100;
mediaPlayer?.SeekTo(pos, MediaPlayerSeekMode.Closest);
UpdatePlaybackState(MediaPlayerState, pos);
mediaPlayer?.SeekTo(position, MediaPlayerSeekMode.Closest);
UpdatePlaybackState(MediaPlayerState, position);
});
}

Expand Down
16 changes: 6 additions & 10 deletions Dimmer/Platforms/Android/MAudioLib/NativeAudioService.android.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,7 @@ public double CurrentPosition
// Return the current position in seconds (convert from milliseconds)
return mediaPlayer?.CurrentPosition / 1000.0 ?? _currentPosInMs / 1000.0;
}
set
{
// Store the value in milliseconds in the local variable
_currentPosInMs = value * 1000;
}

}

public double Volume
Expand Down Expand Up @@ -89,10 +85,10 @@ public Task PauseAsync()
return Task.CompletedTask;
}

public async Task PlayAsync(bool IsFromUser=false)
public async Task PlayAsync(double position = 0, bool IsFromUser = false)
{
instance.Binder.GetMediaPlayerService().currentPositionInMs = 23;
await instance.Binder.GetMediaPlayerService().Play((int)CurrentPosition);
var posInMs = (int)(position * Duration * 1000);
await instance.Binder.GetMediaPlayerService().Play((int)posInMs);
}

Task SetMuted(bool value)
Expand Down Expand Up @@ -134,8 +130,8 @@ Task SetVolume(double volume, double balance)

public async Task<bool> SetCurrentTime(double position)
{
position = (position / 100) * Duration;
var posInMs = (int)position * 1000;
//position = (position) * Duration;
var posInMs = (int)(position * Duration * 1000);
if (mediaPlayer is null)
{
Debug.WriteLine("no media");
Expand Down
71 changes: 33 additions & 38 deletions Dimmer/Platforms/Windows/NativeAudioService.windows.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,21 +43,7 @@ private void OnPropertyChanged(string propertyName)
//}

public double Duration => mediaPlayer?.NaturalDuration.TotalSeconds ?? 0;

private double _currentPosInSeconds;
public double CurrentPosition
{
get
{
// Return the current position in seconds using mediaPlayer's position, or the stored value if mediaPlayer is null
return mediaPlayer?.Position.TotalSeconds ?? _currentPosInSeconds;
}
set
{
// Store the value directly in seconds in the local variable
_currentPosInSeconds = value;
}
}
public double CurrentPosition => mediaPlayer?.Position.TotalSeconds ?? 0;
public double Volume
{
get => mediaPlayer?.Volume ?? 0;
Expand All @@ -67,7 +53,7 @@ public double Volume
if (mediaPlayer is not null)
{
mediaPlayer.Volume = Math.Clamp(value, 0, 1);
}
}
}
}
public bool Muted
Expand Down Expand Up @@ -96,11 +82,12 @@ public Task PauseAsync()
return Task.CompletedTask;
}

public Task PlayAsync(bool IsFromUser=false)
public Task PlayAsync(double position = 0, bool IsFromUser = false)
{
position = position * Duration;
if (mediaPlayer != null && IsFromUser)
{
mediaPlayer.Position = TimeSpan.FromSeconds(CurrentPosition);
mediaPlayer.Position = TimeSpan.FromSeconds(position);
mediaPlayer.Play();
IsPlaying = true;
IsPlayingChanged.Invoke(this, true);
Expand All @@ -124,13 +111,13 @@ public Task DisposeAsync()
mediaPlayer?.Dispose();
return Task.CompletedTask;
}
private MediaPlaybackItem mediaPlaybackItem(MediaPlay media)
private MediaPlaybackItem MediaPlaybackItem(MediaPlay media)
{
var mediaItem = new MediaPlaybackItem(media.Stream == null ? MediaSource.CreateFromUri(new Uri(media.URL)) : MediaSource.CreateFromStream(media.Stream?.AsRandomAccessStream(), string.Empty));
var props = mediaItem.GetDisplayProperties();

props.Type = MediaPlaybackType.Music;

if (media.Name != null)
props.MusicProperties.Title = media.Name;
if (media.Author != null)
Expand All @@ -157,30 +144,38 @@ private RandomAccessStreamReference ConvertToRandomAccessStreamReference(byte[]

public async Task InitializeAsync(MediaPlay media)
{
if (mediaPlayer == null)
try
{
mediaPlayer = new MediaPlayer
if (mediaPlayer == null)
{
Source = mediaPlaybackItem(media),
AudioCategory = MediaPlayerAudioCategory.Media
};
mediaPlayer = new MediaPlayer
{
Source = MediaPlaybackItem(media),
AudioCategory = MediaPlayerAudioCategory.Media
};

mediaPlayer.CommandManager.PreviousReceived += CommandManager_PreviousReceived;
mediaPlayer.CommandManager.PreviousBehavior.EnablingRule = MediaCommandEnablingRule.Always;
mediaPlayer.CommandManager.ShuffleBehavior.EnablingRule = MediaCommandEnablingRule.Always;

mediaPlayer.CommandManager.NextReceived += CommandManager_NextReceived;
mediaPlayer.CommandManager.NextBehavior.EnablingRule = MediaCommandEnablingRule.Always;

mediaPlayer.CommandManager.PreviousReceived += CommandManager_PreviousReceived;
mediaPlayer.CommandManager.PreviousBehavior.EnablingRule = MediaCommandEnablingRule.Always;
mediaPlayer.CommandManager.PlayReceived += CommandManager_PlayReceived;

mediaPlayer.CommandManager.NextReceived += CommandManager_NextReceived;
mediaPlayer.CommandManager.NextBehavior.EnablingRule = MediaCommandEnablingRule.Always;
mediaPlayer.CommandManager.PauseReceived += CommandManager_PauseReceived;
mediaPlayer.MediaEnded += MediaPlayer_MediaEnded;

mediaPlayer.CommandManager.PlayReceived += CommandManager_PlayReceived;

mediaPlayer.CommandManager.PauseReceived += CommandManager_PauseReceived;
mediaPlayer.MediaEnded += MediaPlayer_MediaEnded;

}
else
{
await PauseAsync();
mediaPlayer.Source = MediaPlaybackItem(media);
}
}
else
catch (Exception ex)
{
await PauseAsync();
mediaPlayer.Source = mediaPlaybackItem(media);
await Shell.Current.DisplayAlert("Oops! An Error Occured!", "This is a very very rare error but doesn't affect the app much, Carry On :D", "OK Thanks");
}
}

Expand All @@ -192,7 +187,7 @@ private void MediaPlayer_MediaEnded(MediaPlayer sender, object args)
}
private void CommandManager_NextReceived(MediaPlaybackCommandManager sender, MediaPlaybackCommandManagerNextReceivedEventArgs args)
{

PlayNext?.Invoke(sender, EventArgs.Empty);
}
private void CommandManager_PreviousReceived(MediaPlaybackCommandManager sender, MediaPlaybackCommandManagerPreviousReceivedEventArgs args)
Expand Down
Loading

0 comments on commit a688ac6

Please sign in to comment.