2 * Copyright(c) 2024 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 : IDisposable
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)
62 sampleRate = CurrentAudioOptions.SampleRate;
64 audioPlayback = new AudioPlayback(sampleRate, CurrentAudioOptions.Channel, CurrentAudioOptions.SampleType);
68 Log.Error(LogTag, $"Failed to create AudioPlayback. {e.Message}");
71 if (audioPlayback != null)
73 audioPlayback.Prepare();
74 audioPlayback.BufferAvailable += (sender, args) =>
76 if (audioStream.Position == audioStream.Length)
83 var buffer = new byte[args.Length];
84 audioStream.Read(buffer, 0, args.Length);
85 audioPlayback.Write(buffer);
89 Log.Error(LogTag, $"Failed to write. {e.Message}");
93 audioStream = new MemoryStream(audioBytes);
99 if (audioPlayback != null)
101 audioPlayback.Pause();
105 Log.Error(LogTag, $"audioPlayBack is null");
111 if (audioPlayback != null)
113 audioPlayback.Pause();
118 Log.Error(LogTag, $"audioPlayBack is null");
122 public void Dispose()
126 audioStream?.Flush();
127 audioStream?.Dispose();
131 private void Destroy()
133 audioPlayback?.Unprepare();
134 audioPlayback?.Dispose();
135 audioPlayback = null;