Wednesday, June 27, 2012

How to route a mono sound from an android device to a handset/handfree

Today i was doing an RnD to route a mono sound from an android device to a handsfree/handset and after googling many things and trying out a few i was able to come up with a simple solution using BluetoothHandsfree profile.


Here is a code snippet:
<manifest>

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

.................

BluetoothAdapter mBluetoothAdapter;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
toast("Device does not support Bluetooth");
} else {
toast("Bluetooth is supported");
if (!mBluetoothAdapter.isEnabled()) {
toast("Requesting for Bluetooth");
Intent discoverableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivityForResult(discoverableIntent, REQUEST_ENABLE_BT);
} else {
toast("Bluetooth Enabled");
}
}

mBluetoothAdapter.getProfileProxy(getApplicationContext(),
mProfileListener, BluetoothProfile.HEADSET);

private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.HEADSET) {
mBluetoothHeadset = (BluetoothHeadset) proxy;
Log.i(tag, "***** Headset proxy obtained *****");
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.startBluetoothSco();
audioManager.setBluetoothScoOn(true);

short[] soundData = new short[8000 * 20];
for (int iii = 0; iii < 20 * 8000; iii++) {
soundData[iii] = 32767; // High Note
iii++;
soundData[iii] = 32767; // High Note
iii++;
soundData[iii] = -32768; // Low Note
iii++;
soundData[iii] = -32768; // Low Note
}

AudioTrack audioTrack = new AudioTrack(
AudioManager.STREAM_VOICE_CALL, 8000,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, soundData.length
* Short.SIZE, AudioTrack.MODE_STATIC);
audioTrack.write(soundData, 0, soundData.length);
audioTrack.play();
}
}

public void onServiceDisconnected(int profile) {
if (profile == BluetoothProfile.HEADSET) {
mBluetoothHeadset = null;
Log.i(tag, "***** Headset Disconnected *****");
}
}
};

After running this code in an activity a buzz sound can be listened in a headset/handsfree.




1 comment:

  1. Thanks!

    When I try to do this to an already playing AudioTrack the audio soon routes to headset, but the audio starts to skip after less than a second.

    I also cannot find a way to route an AudioRecord from the headset mic. :(

    ReplyDelete

How to install node using Brew

This article talks about some simple steps to follow to install node using Brew . Though there are many other ways to do it but the method ...