Release 4.0.0-preview1-00201
[platform/core/csapi/tizenfx.git] / src / Tizen.Multimedia.AudioIO / TonePlayer / TonePlayer.cs
1 /*
2  * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the License);
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an AS IS BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 using System;
18 using System.Threading;
19 using System.Threading.Tasks;
20 using Native = Interop.TonePlayer;
21
22 namespace Tizen.Multimedia
23 {
24     /// <summary>
25     /// Provides the ability to play a tone.
26     /// </summary>
27     public static class TonePlayer
28     {
29         /// <summary>
30         /// Plays a tone, asynchronously.
31         /// </summary>
32         /// <param name="tone">A <see cref="ToneType"/> to play.</param>
33         /// <param name="streamPolicy">A <see cref="AudioStreamPolicy"/>.</param>
34         /// <param name="durationMilliseconds">The tone duration in milliseconds. -1 indicates an infinite duration.</param>
35         /// <returns>A task that represents the asynchronous operation.</returns>
36         /// <exception cref="ArgumentException"><paramref name="tone"/> is invalid.</exception>
37         /// <exception cref="ArgumentNullException"><paramref name="streamPolicy"/> is null.</exception>
38         /// <exception cref="ArgumentOutOfRangeException"><paramref name="durationMilliseconds"/> is less than -1.</exception>
39         /// <exception cref="InvalidOperationException">Any invalid operations occurred.</exception>
40         /// <exception cref="NotSupportedException"><paramref name="tone"/> is not a supported type.</exception>
41         /// <exception cref="ObjectDisposedException"><paramref name="streamPolicy"/> has already been disposed of.</exception>
42         public static Task StartAsync(ToneType tone, AudioStreamPolicy streamPolicy,
43             int durationMilliseconds)
44         {
45             return StartAsync(tone, streamPolicy, durationMilliseconds, CancellationToken.None);
46         }
47
48         /// <summary>
49         /// Plays a tone, asynchronously.
50         /// </summary>
51         /// <param name="tone">A <see cref="ToneType"/> to play.</param>
52         /// <param name="streamPolicy">A <see cref="AudioStreamPolicy"/>.</param>
53         /// <param name="durationMilliseconds">The tone duration in milliseconds. -1 indicates an infinite duration.</param>
54         /// <param name="cancellationToken">The cancellation token which can be used to stop playing the tone.</param>
55         /// <returns>A task that represents the asynchronous operation.</returns>
56         /// <exception cref="ArgumentException"><paramref name="tone"/> is invalid.</exception>
57         /// <exception cref="ArgumentNullException"><paramref name="streamPolicy"/> is null.</exception>
58         /// <exception cref="ArgumentOutOfRangeException"><paramref name="durationMilliseconds"/> is less than -1.</exception>
59         /// <exception cref="InvalidOperationException">Any invalid operations occurred.</exception>
60         /// <exception cref="NotSupportedException"><paramref name="tone"/> is not a supported type.</exception>
61         /// <exception cref="ObjectDisposedException"><paramref name="streamPolicy"/> has already been disposed of.</exception>
62         public static Task StartAsync(ToneType tone, AudioStreamPolicy streamPolicy,
63             int durationMilliseconds, CancellationToken cancellationToken)
64         {
65             if (durationMilliseconds < -1)
66             {
67                 throw new ArgumentOutOfRangeException(nameof(durationMilliseconds), durationMilliseconds,
68                     $"{nameof(durationMilliseconds)} can't be less than -1.");
69             }
70
71             if (streamPolicy == null)
72             {
73                 throw new ArgumentNullException(nameof(streamPolicy));
74             }
75
76             ValidationUtil.ValidateEnum(typeof(ToneType), tone, nameof(tone));
77
78             if (cancellationToken.IsCancellationRequested)
79             {
80                 return Task.FromCanceled(cancellationToken);
81             }
82
83             return StartAsyncCore(tone, streamPolicy, durationMilliseconds, cancellationToken);
84         }
85
86         private static async Task StartAsyncCore(ToneType tone, AudioStreamPolicy streamPolicy,
87             int durationMilliseconds, CancellationToken cancellationToken)
88         {
89
90             var tcs = new TaskCompletionSource<bool>();
91
92             Native.Start(tone, streamPolicy.Handle, durationMilliseconds, out var id).
93                 Validate("Failed to play tone.");
94
95             using (RegisterCancellationAction(tcs, cancellationToken, id))
96             {
97                 await WaitForDuration(tcs, cancellationToken, durationMilliseconds);
98
99                 await tcs.Task;
100             }
101         }
102
103         private static async Task WaitForDuration(TaskCompletionSource<bool> tcs,
104             CancellationToken cancellationToken, int durationMilliseconds)
105         {
106             if (durationMilliseconds == -1)
107             {
108                 return;
109             }
110
111             try
112             {
113                 await Task.Delay(durationMilliseconds, cancellationToken);
114                 tcs.TrySetResult(true);
115             }
116             catch (TaskCanceledException)
117             {
118             }
119         }
120
121         private static IDisposable RegisterCancellationAction(TaskCompletionSource<bool> tcs,
122             CancellationToken cancellationToken, int id)
123         {
124             if (cancellationToken.CanBeCanceled == false)
125             {
126                 return null;
127             }
128
129             return cancellationToken.Register(() =>
130             {
131                 Native.Stop(id).Validate("Failed to cancel");
132                 tcs.TrySetCanceled();
133             });
134         }
135     }
136 }
137