2 * Copyright(c) 2023 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 using Tizen.Multimedia;
22 using static Tizen.AIAvatar.AIAvatar;
24 namespace Tizen.AIAvatar
26 internal class AudioPlayer
28 private AudioPlayback audioPlayback;
29 private MemoryStream audioStream;
31 internal AudioPlayer()
35 internal void PlayAsync(byte[] buffer, int sampleRate = 0)
37 if (audioPlayback == null)
39 Play(buffer, sampleRate);
43 audioPlayback.Write(buffer);
47 internal void Play(byte[] audioBytes, int sampleRate = 0)
49 if (audioBytes == null)
56 if (audioPlayback != null)
58 DestroyAudioPlayback();
62 sampleRate = CurrentAudioOptions.SampleRate;
64 audioPlayback = new AudioPlayback(sampleRate, CurrentAudioOptions.Channel, CurrentAudioOptions.SampleType);
68 Log.Error(LogTag, $"Failed to create AudioPlayback. {e.Message}");
72 if (audioPlayback != null)
74 audioPlayback.Prepare();
75 audioPlayback.BufferAvailable += (sender, args) =>
77 if (audioStream.Position == audioStream.Length)
84 var buffer = new byte[args.Length];
85 audioStream.Read(buffer, 0, args.Length);
86 audioPlayback.Write(buffer);
90 Log.Error(LogTag, $"Failed to write. {e.Message}");
94 audioStream = new MemoryStream(audioBytes);
100 if (audioPlayback != null)
102 audioPlayback.Pause();
106 Log.Error(LogTag, $"audioPlayBack is null");
112 if (audioPlayback != null)
114 audioPlayback.Pause();
115 DestroyAudioPlayback();
119 Log.Error(LogTag, $"audioPlayBack is null");
123 internal void Destroy()
125 DestroyAudioPlayback();
128 private void DestroyAudioPlayback()
130 audioPlayback?.Unprepare();
131 audioPlayback?.Dispose();
132 audioPlayback = null;