Free Shipping

Secure Payment

easy returns

24/7 support

  • Home
  • Blog
  • How To Detect The Speaker In Android Wearable Devices

How To Detect The Speaker In Android Wearable Devices

 July 20  | 0 Comments

About Speaker

Google has launched a new update in Android Wearables which comes with some new exciting features and speaker is one amongst them. This is been introduced in only a few devices. Speaker in wearable devices shows how wearables use Android API to play sound through device’s speaker.
Android Wearable devices support the following companies products:

  • LG Watch
  • Huwaie Watch
  • Asus Zenwatch 2
  • Fossil Q Gen 2

Functions of Speaker in an Android Wearable Device

A user can perform the following functions using android wearable devices with the speaker:

  • Allows users to set audio alarms and different notifications from android wearable apps
  • Plays Music
  • Records an audio
  • Gives an extra dimension of engagement with the user

In order to record the audio from the microphone on a wearable device, a user must take necessary permission to use the microphone in the application.
Let’s see how to detect speaker in the wearable devices with the help of a simple application.

Simple Application Explained with Code Snippets

Here, we are going to create a simple application with three buttons:

  1. Play
  2. Audio record
  3. Play the sample mp3 file

Here, we can easily record the voice using the microphone on wear device and play the recorded audio if the wearable device has a built-in speaker.
Here is the step by step procedure to detect speaker in Android Wearable devices.

  1. Create an Application AndroidWearSpeakerExample in an Android Studio with an updated
  2. Choose the Wearable device while creating a project and select Blank Wear Activity and then finish.
  3. Write a code in AndroidManifest.xml to get the permission to use the microphone for audio recording in AndroidManifest.xml.

Requirements

Here are the necessary files  required to build a simple project on the speaker:

1. AndroidManifest.xml

This file uses the permission to record audio. The sample code helps you to record.

<uses-permission android:name="android.permission.RECORD_AUDIO" />

2. res/raw

Create a folder raw into res and put the mp3 file to play a sample audio.

3. activity_main.xml

This is our main layout file which shows the image view for the following:

  • Mic
  • Play
  • Music

In addition, it also includes the progress bar which shows the progress of audio recording.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/background_color">
<View
android:id="@+id/circle"
android:layout_width="140dp"
android:layout_height="140dp"
android:layout_centerInParent="true"
android:background="@drawable/circle" />
<View
android:id="@+id/center"
android:layout_width="1dp"
android:layout_height="1dp"
android:layout_centerInParent="true"
android:visibility="invisible" />
<ImageView
android:id="@+id/iv_mic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/center"
android:layout_centerHorizontal="true"
android:layout_marginBottom="13dp"
android:src="@drawable/ic_mic_32dp" />
<ImageView
android:id="@+id/iv_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/center"
android:layout_marginRight="13dp"
android:layout_marginTop="12dp"
android:layout_toLeftOf="@+id/center"
android:src="@drawable/ic_play_arrow_32dp" />
<ImageView
android:id="@+id/iv_music"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/center"
android:layout_marginLeft="13dp"
android:layout_marginTop="12dp"
android:layout_toRightOf="@+id/center"
android:src="@drawable/ic_audiotrack_32dp" />
<ProgressBar
android:id="@+id/progressbar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="@+id/circle"
android:layout_alignEnd="@+id/circle"
android:layout_below="@+id/circle"
android:progressTint="@color/progressbar_tint"
android:progressBackgroundTint="@color/progressbar_background_tint"
android:layout_marginTop="5dp"
android:visibility="invisible" />
</RelativeLayout>
<ImageView
android:id="@+id/iv_expanded"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="center"
android:visibility="invisible" />
</FrameLayout>

 4. UIAnimation.java

This file is a helper class which shows the UI Animation when a user clicks on any of the three icons. Now, add the below code snippet.
Initialize:

private AnimatorSet mCurrentAnimator;
private final int[] mLargeDrawables = new int[]{R.drawable.ic_mic_120dp,
R.drawable.ic_play_arrow_120dp, R.drawable.ic_audiotrack_120dp};
private final ImageView[] mThumbs;
private ImageView expandedImageView;
private final View mContainerView;
private final int mAnimationDurationTime;
private UIStateListener mListener;
private UIState mState = UIState.HOME;Now, set the listener on images.
mThumbs[0].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
zoomImageFromThumb(0);
}
});

In order to set the properties, write the code in zoomImageFromThumb() method.

5. SoundRecorder.java

This helper class provides methods to record the audio using the microphone to internal storage and then playback the same recorded file.
Initialize:

private static final int RECORDING_RATE = 8000; // can go up to 44K, if needed
private static final int CHANNEL_IN = AudioFormat.CHANNEL_IN_MONO;
private static final int CHANNELS_OUT = AudioFormat.CHANNEL_OUT_MONO;
private static final int FORMAT = AudioFormat.ENCODING_PCM_16BIT;
private static int BUFFER_SIZE = AudioRecord
.getMinBufferSize(RECORDING_RATE, CHANNEL_IN, FORMAT);
private final String mOutputFileName;
private final AudioManager mAudioManager;
private final Handler mHandler;
private final Context mContext;
private State mState = State.IDLE;
private OnVoicePlaybackStateChangedListener mListener;
private AsyncTask<Void, Void, Void> mRecordingAsyncTask;
private AsyncTask<Void, Void, Void> mPlayingAsyncTask;
Add the code to start the mic recording.
mRecordingAsyncTask = new AsyncTask<Void, Void, Void>() {
private AudioRecord mAudioRecord;@Override
protected Void doInBackground(Void... params) {
mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
RECORDING_RATE, CHANNEL_IN, FORMAT, BUFFER_SIZE * 3);
BufferedOutputStream bufferedOutputStream = null;
try {
bufferedOutputStream = new BufferedOutputStream(
mContext.openFileOutput(mOutputFileName, Context.MODE_PRIVATE));
byte[] buffer = new byte[BUFFER_SIZE];
mAudioRecord.startRecording();
while (!isCancelled()) {
int read = mAudioRecord.read(buffer, 0, buffer.length);
bufferedOutputStream.write(buffer, 0, read);
}
} catch (IOException | NullPointerException | IndexOutOfBoundsException e) {
Log.e(TAG, "Failed to record data: " + e);
} finally {
if (bufferedOutputStream != null) {
try {
bufferedOutputStream.close();
} catch (IOException e) {
            }
}
mAudioRecord.release();
mAudioRecord = null;
}
return null;
}
Add the following code snippet to playback the recorded audio file.final int intSize = AudioTrack.getMinBufferSize(RECORDING_RATE, CHANNELS_OUT, FORMAT);
mPlayingAsyncTask = new AsyncTask<Void, Void, Void>() {
private AudioTrack mAudioTrack;@Override
protected void onPreExecute() {
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0 );
mState = State.PLAYING;
}
@Override
protected Void doInBackground(Void... params) {
try {
mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, RECORDING_RATE,
CHANNELS_OUT, FORMAT, intSize, AudioTrack.MODE_STREAM);
byte[] buffer = new byte[intSize * 2];
FileInputStream in = null;
BufferedInputStream bis = null;
mAudioTrack.setVolume(AudioTrack.getMaxVolume());
mAudioTrack.play();
try {
in = mContext.openFileInput(mOutputFileName);
bis = new BufferedInputStream(in);
int read;
while (!isCancelled() && (read = bis.read(buffer, 0, buffer.length)) > 0) {
mAudioTrack.write(buffer, 0, read);
}
} catch (IOException e) {
Log.e(TAG, "Failed to read the sound file into a byte array", e);
} finally {
try {
if (in != null) {
in.close();
}
if (bis != null) {
bis.close();
}
} catch (IOException e) {}
mAudioTrack.release();
}
} catch (IllegalStateException e) {
Log.e(TAG, "Failed to start playback", e);
}
return null;
}

6. MainActivity.java

This is the main activity file which first detects the speaker then shows the UI with three icons. The user can perform the following functions:

  • Record audio up to 10 seconds
  • Playback the recorded audio
  • Play the music included in the application

Initialize

private static final int PERMISSIONS_REQUEST_CODE = 100;
private static final long COUNT_DOWN_MS = TimeUnit.SECONDS.toMillis(10);
private static final long MILLIS_IN_SECOND = TimeUnit.SECONDS.toMillis(1);
private static final String VOICE_FILE_NAME = "audiorecord.pcm";
private MediaPlayer mMediaPlayer;
private AppState mState = AppState.READY;
private UIAnimation.UIState mUiState = UIAnimation.UIState.HOME;
private SoundRecorder mSoundRecorder;private UIAnimation mUIAnimation;
private ProgressBar mProgressBar;
private CountDownTimer mCountDownTimer;
Add the below code snippet in onCreate(..){..}
mProgressBar = (ProgressBar) findViewById(R.id.progressbar);
mProgressBar.setMax((int) (COUNT_DOWN_MS / MILLIS_IN_SECOND));
Now, determine that the device has a built-in speaker or not.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PackageManager packageManager = getPackageManager();
if (!packageManager.hasSystemFeature(PackageManager.FEATURE_AUDIO_OUTPUT)) {
return false;
}udioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
AudioDeviceInfo[] devices = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS);
for (AudioDeviceInfo device : devices) {
if (device.getType() == AudioDeviceInfo.TYPE_BUILTIN_SPEAKER) {
return true;
}
}
}
return false;
To play the mp3 file which is embedded in the application.

if (mMediaPlayer == null) {
mMediaPlayer = MediaPlayer.create(this, R.raw.sound);
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Log.d(TAG, "Music Finished");
mUIAnimation.transitionToHome();
}
});
}
mMediaPlayer.start();

If there are any changes in UI animation for mic and play button, then it calls the SoundRecorder class to play and record the audio as discussed in the SoundRecorder java file.
Now, run the application and see the output.

>