forked from VladislavAntonyuk/MauiSamples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainPage.xaml.cs
88 lines (80 loc) · 2.2 KB
/
MainPage.xaml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
namespace MauiBells;
using Plugin.Maui.Audio;
public sealed partial class MainPage : ContentPage, IDisposable
{
private IAudioPlayer? audioPlayer;
DateTime lastShakeDetected;
public MainPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
if (Accelerometer.Default is { IsSupported: true, IsMonitoring: false })
{
Accelerometer.Default.ShakeDetected += ShakeDetected;
Accelerometer.Default.ReadingChanged += ReadingChanged;
Accelerometer.Default.Start(SensorSpeed.UI);
}
Task.Factory.StartNew(async () =>
{
// "https://jesusful.com/wp-content/uploads/music/2020/09/Boney_M_-_Jingle_Bells_(Jesusful.com).mp3"
var fileStream = await FileSystem.OpenAppPackageFileAsync("jingle_bells.mp3");
audioPlayer = AudioManager.Current.CreatePlayer(fileStream);
while (true)
{
var dateTime = DateTime.Now;
var tasks = new[]
{
Flip(Year, dateTime.Year),
Flip(Month, dateTime.Month),
Flip(Day, dateTime.Day),
Flip(Hour, dateTime.Hour),
Flip(Minute, dateTime.Minute),
Flip(Second, dateTime.Second)
};
await Task.WhenAll(tasks);
if (lastShakeDetected + TimeSpan.FromSeconds(5) < DateTime.Now && audioPlayer is { IsPlaying: true })
{
audioPlayer.Pause();
}
}
});
}
private async void ReadingChanged(object? sender, AccelerometerChangedEventArgs e)
{
var angle = DeviceDisplay.Current.MainDisplayInfo.Orientation == DisplayOrientation.Portrait ?
e.Reading.Acceleration.X :
e.Reading.Acceleration.Y;
await Bell.RotateTo(angle * 180 / Math.PI);
}
private void ShakeDetected(object? sender, EventArgs e)
{
lastShakeDetected = DateTime.Now;
if (audioPlayer is { IsPlaying: false })
{
audioPlayer.Play();
}
}
public void Dispose()
{
Accelerometer.Default.ShakeDetected -= ShakeDetected;
Accelerometer.Default.ReadingChanged -= ReadingChanged;
Accelerometer.Default.Stop();
audioPlayer?.Dispose();
}
async Task Flip(Label label, int text)
{
var textString = text.ToString();
if (label.Text != textString)
{
await label.RotateXTo(90, 500);
await Dispatcher.DispatchAsync(() =>
{
label.Text = textString;
});
await label.RotateXTo(0, 500);
}
}
}