Release 4.0.0-preview1-00051
[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
21 namespace Tizen.Multimedia
22 {
23     /// <summary>
24     /// Provides the ability to play a tone.
25     /// </summary>
26     public static class TonePlayer
27     {
28         /// <summary>
29         /// Plays a tone, asynchronously.
30         /// </summary>
31         /// <param name="tone">A <see cref="ToneType"/> to play.</param>
32         /// <param name="streamPolicy">A <see cref="AudioStreamPolicy"/>.</param>
33         /// <param name="durationMilliseconds">The tone duration in milliseconds. -1 indicates an infinite duration.</param>
34         /// <returns>A task that represents the asynchronous operation.</returns>
35         /// <exception cref="ArgumentException"><paramref name="tone"/> is invalid.</exception>
36         /// <exception cref="ArgumentNullException"><paramref name="streamPolicy"/> is null.</exception>
37         /// <exception cref="ArgumentOutOfRangeException"><paramref name="durationMilliseconds"/> is less than -1.</exception>
38         /// <exception cref="InvalidOperationException">Any invalid operations occurred.</exception>
39         /// <exception cref="NotSupportedException"><paramref name="tone"/> is not a supported type.</exception>
40         /// <exception cref="ObjectDisposedException"><paramref name="streamPolicy"/> has already been disposed.</exception>
41         public static Task StartAsync(ToneType tone, AudioStreamPolicy streamPolicy,
42             int durationMilliseconds)
43         {
44             return StartAsync(tone, streamPolicy, durationMilliseconds, CancellationToken.None);
45         }
46
47         /// <summary>
48         /// Plays a tone, asynchronously.
49         /// </summary>
50         /// <param name="tone">A <see cref="ToneType"/> to play.</param>
51         /// <param name="streamPolicy">A <see cref="AudioStreamPolicy"/>.</param>
52         /// <param name="durationMilliseconds">The tone duration in milliseconds. -1 indicates an infinite duration.</param>
53         /// <param name="cancellationToken">The cancellation token which can be used to stop playing the tone.</param>
54         /// <returns>A task that represents the asynchronous operation.</returns>
55         /// <exception cref="ArgumentException"><paramref name="tone"/> is invalid.</exception>
56         /// <exception cref="ArgumentNullException"><paramref name="streamPolicy"/> is null.</exception>
57         /// <exception cref="ArgumentOutOfRangeException"><paramref name="durationMilliseconds"/> is less than -1.</exception>
58         /// <exception cref="InvalidOperationException">Any invalid operations occurred.</exception>
59         /// <exception cref="NotSupportedException"><paramref name="tone"/> is not a supported type.</exception>
60         /// <exception cref="ObjectDisposedException"><paramref name="streamPolicy"/> has already been disposed.</exception>
61         public static Task StartAsync(ToneType tone, AudioStreamPolicy streamPolicy,
62             int durationMilliseconds, CancellationToken cancellationToken)
63         {
64             if (durationMilliseconds < -1)
65             {
66                 throw new ArgumentOutOfRangeException(nameof(durationMilliseconds), durationMilliseconds,
67                     $"{nameof(durationMilliseconds)} can't be less than -1.");
68             }
69
70             if (streamPolicy == null)
71             {
72                 throw new ArgumentNullException(nameof(streamPolicy));
73             }
74
75             ValidationUtil.ValidateEnum(typeof(ToneType), tone, nameof(tone));
76
77             if (cancellationToken.IsCancellationRequested)
78             {
79                 return Task.FromCanceled(cancellationToken);
80             }
81
82             return StartAsyncCore(tone, streamPolicy, durationMilliseconds, cancellationToken);
83         }
84
85         private static async Task StartAsyncCore(ToneType tone, AudioStreamPolicy streamPolicy,
86             int durationMilliseconds, CancellationToken cancellationToken)
87         {
88
89             var tcs = new TaskCompletionSource<bool>();
90
91             Interop.TonePlayer.Start(tone, streamPolicy.Handle, durationMilliseconds, out var id).
92                 Validate("Failed to play tone.");
93
94             using (RegisterCancellationAction(tcs, cancellationToken, id))
95             {
96                 await WaitForDuration(tcs, cancellationToken, durationMilliseconds);
97
98                 await tcs.Task;
99             }
100         }
101
102         private static async Task WaitForDuration(TaskCompletionSource<bool> tcs,
103             CancellationToken cancellationToken, int durationMilliseconds)
104         {
105             if (durationMilliseconds == -1)
106             {
107                 return;
108             }
109
110             try
111             {
112                 await Task.Delay(durationMilliseconds, cancellationToken);
113                 tcs.TrySetResult(true);
114             }
115             catch (TaskCanceledException)
116             {
117             }
118         }
119
120         private static IDisposable RegisterCancellationAction(TaskCompletionSource<bool> tcs,
121             CancellationToken cancellationToken, int id)
122         {
123             if (cancellationToken.CanBeCanceled == false)
124             {
125                 return null;
126             }
127
128             return cancellationToken.Register(() =>
129             {
130                 Interop.TonePlayer.Stop(id).Validate("Failed to cancel");
131                 tcs.TrySetCanceled();
132             });
133         }
134     }
135 }
136