1 /* 2 * Copyright (C) 2022 The Android Open Source Project 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 package android.voiceinteraction.common; 17 18 import static com.google.common.truth.Truth.assertThat; 19 20 import android.media.AudioFormat; 21 import android.os.ParcelFileDescriptor; 22 23 import java.io.ByteArrayOutputStream; 24 import java.io.IOException; 25 import java.io.InputStream; 26 import java.io.OutputStream; 27 28 public class AudioStreamHelper { 29 30 public static final byte[] FAKE_INITIAL_AUDIO_DATA = 31 new byte[]{'h', 'o', 't', 'w', 'o', 'r', 'd', '!'}; 32 public static final byte[] FAKE_HOTWORD_AUDIO_STREAM_DATA = 33 new byte[]{'s', 't', 'r', 'e', 'a', 'm', '!'}; 34 public static final AudioFormat FAKE_AUDIO_FORMAT = 35 new AudioFormat.Builder() 36 .setSampleRate(32000) 37 .setEncoding(AudioFormat.ENCODING_PCM_16BIT) 38 .setChannelMask(AudioFormat.CHANNEL_IN_MONO).build(); 39 createFakeAudioStreamPipe(byte[] audioData)40 public static ParcelFileDescriptor[] createFakeAudioStreamPipe(byte[] audioData) 41 throws IOException { 42 ParcelFileDescriptor[] parcelFileDescriptors = ParcelFileDescriptor.createPipe(); 43 try (OutputStream fos = 44 new ParcelFileDescriptor.AutoCloseOutputStream(parcelFileDescriptors[1])) { 45 fos.write(audioData); 46 } 47 return parcelFileDescriptors; 48 } 49 closeAudioStreamPipe(ParcelFileDescriptor[] parcelFileDescriptors)50 public static void closeAudioStreamPipe(ParcelFileDescriptor[] parcelFileDescriptors) 51 throws IOException { 52 if (parcelFileDescriptors != null) { 53 parcelFileDescriptors[0].close(); 54 parcelFileDescriptors[1].close(); 55 } 56 } 57 assertAudioStream(ParcelFileDescriptor audioStream, byte[] expected)58 public static void assertAudioStream(ParcelFileDescriptor audioStream, byte[] expected) 59 throws IOException { 60 try (InputStream audioSource = new ParcelFileDescriptor.AutoCloseInputStream(audioStream)) { 61 ByteArrayOutputStream result = new ByteArrayOutputStream(); 62 byte[] buffer = new byte[1024]; 63 int count; 64 while ((count = audioSource.read(buffer)) != -1) { 65 result.write(buffer, 0, count); 66 } 67 assertThat(result.toByteArray()).isEqualTo(expected); 68 } 69 } 70 } 71