/* * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Native = Interop.WavPlayer; namespace Tizen.Multimedia { /// /// Provides the ability to play a wav file. /// public static class WavPlayer { /// /// Plays a wav file based on the specified . /// /// A task that represents the asynchronous operation. /// A file path to play. /// A . /// /// is null. /// -or- /// is null. /// /// An internal error occurs. /// does not exists. /// The format of is not supported. /// has already been disposed of. public static Task StartAsync(string path, AudioStreamPolicy streamPolicy) { return StartAsync(path, streamPolicy, CancellationToken.None); } /// /// Plays a wav file based on the specified . /// /// A task that represents the asynchronous operation. /// A file path to play. /// A . /// A cancellation token which can be used to stop. /// /// is null. /// -or- /// is null. /// /// An internal error occurs. /// does not exists. /// The format of is not supported. /// has already been disposed of. public static Task StartAsync(string path, AudioStreamPolicy streamPolicy, CancellationToken cancellationToken) { if (path == null) { throw new ArgumentNullException(nameof(path)); } if (streamPolicy == null) { throw new ArgumentNullException(nameof(streamPolicy)); } if (File.Exists(path) == false) { throw new FileNotFoundException("File does not exists.", path); } return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : StartAsyncCore(path, streamPolicy, cancellationToken); } private static async Task StartAsyncCore(string path, AudioStreamPolicy streamPolicy, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource(); Native.WavPlayerCompletedCallback cb = (id_, _) => tcs.TrySetResult(true); using (ObjectKeeper.Get(cb)) { Native.Start(path, streamPolicy.Handle, cb, IntPtr.Zero, out var id). Validate("Failed to play."); using (RegisterCancellationAction(tcs, cancellationToken, id)) { await tcs.Task; } } } private static IDisposable RegisterCancellationAction(TaskCompletionSource tcs, CancellationToken cancellationToken, int id) { if (cancellationToken.CanBeCanceled == false) { return null; } return cancellationToken.Register(() => { Native.Stop(id).Validate("Failed to cancel"); tcs.TrySetCanceled(); }); } } }