Bluetooth audio android to android

Bluetooth audio streaming between android devices

I made a research on the same topic and found that android devices are a2dp sources and the audio can be streamed only from an a2dp source to an a2dp sink. A2dp sink can be a bluetooth headset or a bluetooth speaker. But my question is then how the android app named «Bluetooth Music Player» works? It allows streaming from one mobile to another. So in this case the listening mobile device must act as a sink. How this is possible? Are they using some other profile instead of a2dp? Ok, that may be a different profile what they are using. Because the application needs to be installed in the client side also. But how it becomes possible to stream voice from a bluetooth microphone to an android device? Please help.

I did not understand what you need to know: sending audio from one Android to another, or sending audio from a standalone Bluetooth microphone to an Android?

Hello Sir, I need your help to steaming audio from one device to another device. Can you please give me any example code for this ? I have asked question : stackoverflow.com/questions/16789394/…

1 Answer 1

Without knowing details about the mentioned Bluetooth Music Player, it seems to use simple Bluetooth data connection, otherwise you would not need to install a client on playing/sending device.

To stream audio from microphone to another device, you can record it on your sending device and send it to the receiving device. You will need to implement a protocol for that purpose.
OR
You can implement an alternative A2DP sink service. This is, what the sink is: a device with a Bluetooth Protocol Stack with an implementation of A2DP Sink.

Edit:
For the case you detailed by your comments, the sending device should be left as-is, without installing any app. That implicitly means that your solution must make use of out-of-the-box Bluetooth functionality of that Android device.
What you can use here is therefor limited to those profiles that Android typically support, which is HSP, HFP and A2DP. Since you obviously want to stream music, A2DP would be your choice.
On the device supposed to receive the audio stream and do the playback, you have to implement a service providing the A2DP sink as an self implemented BluetoothService opening a BluetoothServerSocket on RFCOMM as described in Android documentation.

You will have to spend much effort implementing this, and I am not sure if you will need a license for this.

Источник

Routing audio to Bluetooth Headset (non-A2DP) on Android

I have a non-A2DP single ear BT headset (Plantronics 510) and would like to use it with my Android HTC Magic to listen to low quality audio like podcasts/audio books. After much googling I found that only phone call audio can be routed to the non-A2DP BT headsets. (I would like to know if you have found a ready solution to route all kinds of audio to non-A2DP BT headsets) So I figured, somehow programmatically I can channel the audio to the stream that carries phone call audio. This way I will fool the phone to carry my mp3 audio to my BT headset. I wrote following simple code.

import android.content.*; import android.app.Activity; import android.os.Bundle; import android.media.*; import java.io.*; import android.util.Log; public class BTAudioActivity extends Activity < private static final String TAG = "BTAudioActivity"; private MediaPlayer mPlayer = null; private AudioManager amanager = null; @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.main); amanager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); amanager.setBluetoothScoOn(true); amanager.setMode(AudioManager.MODE_IN_CALL); mPlayer = new MediaPlayer(); try < mPlayer.setDataSource(new FileInputStream( "/sdcard/sample.mp3").getFD()); mPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL); mPlayer.prepare(); mPlayer.start(); >catch(Exception e) < Log.e(TAG, e.toString()); >> @Override public void onDestroy() < mPlayer.stop(); amanager.setMode(AudioManager.MODE_NORMAL); amanager.setBluetoothScoOn(false); super.onDestroy(); >> 
  • Using MediaPlayer’s setAudioStreamType(STREAM_VOICE_CALL)
  • using AudioManager’s setBluetoothScoOn(true)
  • using AudioManager’s setMode(MODE_IN_CALL)
Читайте также:  Передать ноутбука телефон bluetooth

But none of the above worked. If I remove the AudioManager calls in the above code, the audio plays from speaker and if I replace them as shown above then the audio stops coming from speakers, but it doesn’t come through the BT headset. So this might be a partial success.

I have checked that the BT headset works alright with phone calls.

There must be a reason for Android not supporting this. But I can’t let go of the feeling that it is not possible to programmatically reroute the audio. Any ideas?

P.S. above code needs following permission

You may not need to write any code yourself. Simply install a free app which is designed to do what you want. See the Android.SE question: «Is it possible to direct all audio output, including music output, to a Bluetooth headset?» I tried a few different apps. In the end, «Mono Bluetooth Router» was the only one which worked for me.

5 Answers 5

This thread may be long dead but for those who might be trying the same thing, some notes from the AudioManager docs may be useful. It looks like the missing element is the startBluetoothSco() command but there are restrictions on the use of this channel. From the Android Dev site here:

public void startBluetoothSco () Since: API Level 8 Start bluetooth SCO audio connection.

Requires Permission: MODIFY_AUDIO_SETTINGS.

This method can be used by applications wanting to send and received audio to/from a bluetooth SCO headset while the phone is not in call.

As the SCO connection establishment can take several seconds, applications should not rely on the connection to be available when the method returns but instead register to receive the intent ACTION_SCO_AUDIO_STATE_CHANGED and wait for the state to be SCO_AUDIO_STATE_CONNECTED.

As the connection is not guaranteed to succeed, applications must wait for this intent with a timeout.

When finished with the SCO connection or if the establishment times out, the application must call stopBluetoothSco() to clear the request and turn down the bluetooth connection.

Even if a SCO connection is established, the following restrictions apply on audio output streams so that they can be routed to SCO headset: — the stream type must be STREAM_VOICE_CALL — the format must be mono — the sampling must be 16kHz or 8kHz

Читайте также:  Alpine cde 133bt bluetooth

The following restrictions apply on input streams: — the format must be mono — the sampling must be 8kHz

Note that the phone application always has the priority on the usage of the SCO connection for telephony. If this method is called while the phone is in call it will be ignored. Similarly, if a call is received or sent while an application is using the SCO connection, the connection will be lost for the application and NOT returned automatically when the call ends.

See Also stopBluetoothSco() ACTION_SCO_AUDIO_STATE_CHANGED

Note that I have not tested this, I’m just passing along a lead I found in researching a similar project. I think Jayesh was close to the solution and the restrictions above may have been what was keeping it from working.

Источник

Как изменить аудиокодек Bluetooth на Android

Хотите улучшить качество звука в беспроводных наушниках, подключенных к смартфону на базе Android? Чуть ниже мы расскажем, что делать.

Бесспорно, Bluetooth-наушники невероятно удобные, однако они не могут сравниться с проводными аналогами в плане качества звука. Поэтому покупателям всегда приходится выбирать между удобством и звучанием.

К счастью, звук на беспроводных наушниках можно настроить за счет изменения аудиокодека на используемом девайсе. Чуть ниже мы расскажем о различных аудиокодеках, доступных на устройствах на базе Android, а также о том, как их изменить.

Почему стоит изменить аудиокодек Bluetooth

Используемый кодек зависит от того, что именно вы прослушиваете на своих беспроводных наушниках:

  • Если вы хотите слушать музыку Hi-Fi, то нужно установить кодек, обеспечивающий превосходное качество звука.
  • Для звонков нужен кодек, выдающий стабильное звучание. Это касается и фильмов, поскольку при просмотре аудио и видео должны идеально синхронизироваться, что требует кодека с малой задержкой.

Беспроводные наушники – явление достаточно новое (если сравнивать с проводными аналогами), из-за чего не существует идеального кодека, который всегда обеспечивал бы высокое качество звука и минимальную задержку.

Именно поэтому стоит подумать об изменении дефолтного аудиокодека Bluetooth в соответствии с типом прослушиваемой музыки и мощностью сигнала.

Изменение кодека поможет выжать из Bluetooth-наушников максимум, но не стоит забывать, что кодек будет работать только в том случае, если наушники совместимы с ним.

Самые популярные кодеки

Bluetooth codecs explained: LDAC, LDHC, aptX, AAC, LC3 and SBC - Dignited

Прежде чем узнать, как изменить стандартный кодек на смартфоне, важно разобраться, какие типы кодеков существуют, а также с тем, какой из них лучше всего подходит для той или иной цели.

SBC

JLab Go Air Pop Wireless Earbuds Review: Excellence on a Budget

SBC (аббревиатура от Low Complexity Sub-band Coding) – наиболее распространенный кодек. Он установлен на всех аудиоустройствах на базе Android, поддерживающих A2DP (Advanced Audio Distribution Profile) — расширенный профиль передачи аудио.

SBC – это что-то вроде базовой версии всех аудиокодеков. Он предлагает довольно-таки посредственное качество звука и потребляет гораздо меньше энергии.

Он не способен выдавать высококлассный звук и имеет более высокую задержку по сравнению с другими кодеками нашего списка.

Кодек подойдет для обычных пользователей, не сильно заботящихся о высоком качестве звука. Но для игр или просмотра фильмов нужно выбрать что-то другое, поскольку у SBC довольно-таки высокая задержка.

Читайте также:  Настройка bluetooth клавиатуры android

aptX

Qualcomm aptX — это целое семейство кодеков, в которое входят 7 различных версий.

aptX использует адаптивную дифференциальную импульсно-кодовую модуляцию (ADPCM), которая выдает гораздо лучшее качество звука, чем SBC.

На Android-устройствах чаще всего встречаются 3 вариации aptX:

  • aptX: лучшая альтернатива SBC, но всё еще не подойдет тем, кому нужен звук с минимальными потерями.
  • aptX HD: значительное улучшение по сравнению с оригинальной версией, так как качество звука намного лучше, а звук воспроизводится с минимальной задержкой. aptX HD отлично подойдет для прослушивания Hi-Fi аудио и просмотра фильмов.
  • aptX Adaptive: динамически меняет битрейт для более стабильного соединения. Кодек отлично подходит практически для всего: от игр до звонков и просмотра видео. Но среди всех трех опций именно aptX HD выдает лучшее качество звука.

AAC

AAC, сокращенно от Advanced Audio Codec, очень похож на SBC. Он потребляет больше энергии, несмотря на то что воспроизводит звук с потерями. AAC обычно используется в устройствах от компании Apple, поскольку iOS оптимизирована для использования именно этого кодека.

Если же говорить об Android, AAC – последний вариант, который стоит использовать только в том случае, если все другие кодеки несовместимы с вашими наушниками.

AAC не подходит для игр и высококлассного аудио, но для обычного прослушивания музыки кодека более чем достаточно.

LDAC

LDAC, разработанный южнокорейской компанией Sony, похож на aptX Adaptive. Главное отличие заключается в том, что второй автоматически настраивается в зависимости от уровня сигнала, а первый – переключается между тремя предустановленными битрейтами.

LDAC – высококлассный аудиокодек для настоящих ценителей звука, у которого есть лишь один недостаток – очень слабое качество соединения.

Среди плюсов же стоит выделить низкую задержку, благодаря которой кодек отлично подходят для игр и просмотра видео.

LHDC

Кодек LHDC в смартфонах — что это и зачем нужен? | AndroidLime

LHDC, сокращенно от Low-Latency and High-Definition Audio Codec (букв. перевод – кодек высокого разрешения с низкими задержками), был разработан в сотрудничестве Hi-Res Wireless Audio (HWA) и Savitech.

Кодек предназначен для настоящих аудиофилов, поскольку выдает высочайшее качество звука и минимизирует задержку, благодаря чему LHDC отлично подходит для прослушивания Hi-Fi музыки, просмотра видео и игр.

Как изменить аудиокодек Bluetooth на Android

Samsung Galaxy S22 Ultra: Дата выхода, дизайн, поддержка S Pen, новые камеры - AndroidInsider.ru

После того, как вы определились, какой кодек хотите использовать, и какой из них совместим с наушниками и поддерживается смартфоном, можно приступить к его изменению.

Отметим, что на телефоне должна быть установлена версия Android 8.0 или новее.

  • Откройте меню «Настройки» на смартфоне.
  • Перейдите к разделу «Система», а затем «Для разработчиков».
  • Нажмите на пункт «Аудиокодек Bluetooth».
  • Выберите подходящую опцию.

Помимо кодеков из списка, вы можете установить на свое устройство новые. Чтобы включить или отключить их, нужно нажать на «Включить/выключить опциональные кодеки».

За хорошее качество звука нужно бороться

Несмотря на то, что беспроводная технология еще не достигла своего апогея и пока не способна на равных конкурировать с проводным аналогом, вы все равно можете улучшить качество звука и уменьшить задержку за счет изменения стандартного аудиокодека Bluetooth.

Каждый кодек имеет свои преимущества и недостатки, но среди всех вариантов aptX Adaptive и LDAC наиболее близки к идеалу.

Источник

Оцените статью
Adblock
detector