1, 2, 3, 4, A2DP Stream

After a few people asking me how to use the A2DP Sink with BlueZ, I’ve decided to write this mini-tutorial with a step-by-step on how to establish a A2DP stream from any device to a BlueZ-enabled host.

Before we start the hands-on, let’s see a little bit of nomenclature. In our use-case we have an stream being transmitted between two devices through a pipeline. Our pipeline is constructed of the remote host, BlueZ and PulseAudio. Each element of this pipeline has a Source (SRC) and a Sink (SNK) interface. The stream is handled between different elements by being sent from one element’s source to another element’s sink. So, the big picture of our pipeline is something like this (with the stream being represented by an arrow):

Remote-SRC ----> SNK-BlueZ-SRC ----> SNK-PulseAudioBT-SRC

With the PulseAudio bluetooth source being available for applications to connect to it and serve themselves with fresh, just-decoded PCM frames of pure stereo audio. In our example, we gonna add another element to the pipeline tho. In order to able to hear the audio we’re receiving, we gonna connect the PulseAudio bluetooth source to a PulseAudio ALSA sink which pushes the audio out through our soundcard speakers.

PulseAudioBT-SRC ----> SNK-PulseAudioALSA ----> SoundCard

So after these lines on theory, let’s get out hands dirty. First of all, you need a recent version of BlueZ and PulseAudio. BlueZ 4.46 and PulseAudio 0.9.16 should be enough, but I strongly recommend getting the newest releases available by the time you read this. Right now the most recent releases are BlueZ 4.58 and PulseAudio 0.9.21.

  1. PulseAudio must be running with module-bluetooth-discover loaded;
    • This module is automatically loaded on startup with the default configuration;
    • If it’s not loaded you can use pactl to load it manually or configure PulseAudio to load it on startup in /etc/pulse/default.pa;
  2. Enable the Source interface on BlueZ:
    • edit /etc/bluetooth/audio.conf and add the following line: Enable=Source ;
    • restart bluetoothd;
  3. Pair both devices;
  4. On the object path representing the remote host, on org.bluez D-Bus service, call the org.bluez.AudioSource.Connect() method;
    • For the connection to succeed you’ll probably have to grant access on the remote host;
    • When the connection is established, a new card should show up on PulseAudio with one source available;
  5. Connect PulseAudio bluetooth source to PulseAudio ALSA sink;
    • load-module module-loopback source=<name> sink=<name>
    • You can use the line above to load the module-loopback, using pactl (on the command line) or inside pacmd shell;
    • To find out the name of the source and the sink, you can use the commands list-sources and list-sinks inside pacmd shell;
    • This step is only needed if you want to send the audio coming through A2DP to your speakers.

It’s important to remember that the current implementation is working but could see some improvements, so expect to hear some glitches if you go through signal variation. Happy bluetooth audio streaming!

82 responses to “1, 2, 3, 4, A2DP Stream

  1. Paul Ionescu

    Hi

    Can you please give more details on step 4:

    “On the object path representing the remote host, on org.bluez D-Bus service, call the org.bluez.AudioSource.Connect() method;

    * For the connection to succeed you’ll probably have to grant access on the remote host;
    * When the connection is established, a new card should show up on PulseAudio with one source available;

    What commands will accomplish this requirement ?

  2. You can use dbus-send command to call the org.bluez.AudioSource.Connect() method but using d-feet for example a bit easier. It has a graphical interface. Just start it, look for the method, click on it twice and click execute.
    And please let me know if AudioSource exist in your system because I’ve enabled Source interface but unable to find AudioSource interface.

  3. I am using Blueman in Ubuntu 9.10 and tried to connect Audio Source(Till 4th step). It succeded. But while playing song from mobile my sound settings crashes.
    But I am not seeing any details like “a new card should show up on PulseAudio with one source available;”

    Can you please give us your environemnt setup details and phone model used

  4. Finally, It works! Thank you a lot!! Tested on Ubuntu 9.10 with bluez and gnome-bluetooth-manager with the Android phone Motorola Milestone. The sound’s clipping a little bit if I set the milestone to the maximum but no glitches whatsoever, sounds beautiful 🙂
    I’ve done this on my Ubuntu box:
    * apt-get install pulseaudio-module-bluetooth (manually loaded with:
    pactl load-module module-bluetooth-discover

    * D-feet->SystemBus->org.bluez selecting the last path with the interface org.bluez.AudioSource and Connect() (operation timed out but the source is connected and pulseaudio manager see the new input interface).

    * Pulseaudio:
    pactl load-module module-loopback

    *from Volume Control on pulseaudio applet:
    -> Recording->Select All streams-> Loopback to Internal Audio Analog Stereo from (selected my device)

    Now i’ve to automate the connect() procedure because sometimes it looses the connection with pulseaudio even if the device is still paired with the computer on the “Media Audio” profile.

  5. It is great that you bring it up. what bluetooth hardware you are using for this setup?

  6. My dongle is a dlink dbt 122. Nothing fancy 🙂

  7. 1. Has anybody tried running it on an ARM or any other embedded board for that matter ?
    2. Is the source support required for a2dp certification of a product?

  8. The reason why I am asking the second question is I have a samsung phone that I bought a couple of years back and it streams audio from the mobile to bluetooth headphones but it neither records nor has the capability to stream audio from my bluez enabled laptop. But still it bears the bluetooth logo. So it must be a2dp certified … right ? I am very confused now … please help …

  9. techguru, this phone you have may implement and be certified only for certain bluetooth profiles. From you description it seems it supports HSP/HFP only.

  10. Hi jpvrita
    I found that the mobile phone sgh-e840 has many profiles certified. Of which, a2dp source is one. So I think a2dp source and a2dp sink can be certified separately.
    https://www.bluetooth.org/tpg/QLI_viewQDL.cfm?qid=13261

  11. Hello,
    I’ve been trying to connect my phone to my computer. Everything seems to be working fine (connecting, loopback module) until I click on “play” on my phone, then pulseaudio crash with a beautiful:

    module-bluetooth-device.c: Assertion ‘(size_t) decoded == a2dp->frame_length’ failed at modules/bluetooth/module-bluetooth-device.c:1375, function a2dp_process_push(). Aborting.

    Do you have any idea why this is happening?

    Anyway, thanks for all the work you’ve been putting on this, i’m really looking forward to that working on my Linux 😉

  12. I tried this with bluez-4.60 and PulseAudio 0.9.21 on two computers. and pulseaudio crushes with this:
    module-bluetooth-device.c: Assertion ‘(size_t) decoded == a2dp->frame_length’ failed at modules/bluetooth/module-bluetooth-device.c:1367, function a2dp_process_push(). Aborting.
    When i tried to stream sound from phone, same problem..
    Thank You for developing it for linux 😉

  13. ok. now i can send voice from windows to linux and hear it, no more “module-bluetooth-device.c: Assertion ‘(size_t) decoded == a2dp->frame_length’ failed at modules/bluetooth/module-bluetooth-device.c:1367, function a2dp_process_push(). Aborting.” problems.

    I just replaced line in modules/bluetooth/module-bluetooth-device.c:1367 with “pa_assert_fp((size_t) decoded );” and recompiled.

    PS Strange that decoded == 78 and a2dp->frame_length == 148 // problem in this..

  14. Pingback: Ubuntu 蓝牙全攻略 | My Sky

  15. well, I tried doing this, with a variety of hardware, but till now no luck.
    Here’s what I run.
    bluez-svn
    pulseaudio-0.9.21
    My test devices:
    1. a laptop running WinXP and Widcomm stack.
    2. a samsung phone, having a2dp profile.
    I have ensured a2DP streaming works between
    phone —-> winXP laptop.

    Now, when I run bluetoothd, and pulseaudio, and then connect to winXP laptop’s audio service, I’m able to do that successfully.
    When I see the list-sources, or the padevchooser, there is no audio source in there. I do see a “monitor of ” type entry in the sources list. If I change configuration to HFP/HSP, I do get a mono (and low quality audio stream), which I can listen to.

    If I try to connect to my phone, I get get an error.

  16. hi ,paul. I’ve got the same problem.But I can not find the “module-bluetooth-device.c” file.No mention to modify and recompile it , can you just give a detailed illustration?

  17. Paco Soria

    Hello, I have found the same problem. I did as Paulo said before: I compiled pulseaudio sources after modified the line 1367 in modules/bluetooth/module-bluetooth-device.c:
    It was –> pa_memblock_release(memchunk.memblock);
    I put –> pa_assert_fp((size_t) decoded );
    and recompiled, the I only copied the new file module-bluetooth-device.so overwritting the old one. However I’ve got now a new message:

    module-bluetooth-device.c: Assertion ‘u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW’ failed at modules/bluetooth/module-bluetooth-device.c:1064, function hsp_process_push(). Aborting.

    Any hints?

  18. Neural said this on December 23, 2009:
    > I’ve done this on my Ubuntu box:
    > * apt-get install pulseaudio-module-bluetooth (manually loaded with:
    > pactl load-module module-bluetooth-discover

    I use an Ubuntu 10.04. I found that I don’t need that because pulseaudio-module-bluetooth is already installed and automaticatilly loaded. Here is how pactl list sees it:
    Modulo #6
    Nome: module-bluetooth-discover
    Argomento:
    Contatore utilizzi: N/D
    Proprietà:
    module.author = “Joao Paulo Rechi Vita”
    module.description = “Detect available bluetooth audio devices a
    nd load bluetooth audio drivers”
    module.version = “0.9.21-63-gd3efa-dirty”

    > * D-feet->SystemBus->org.bluez selecting the last path with the interface org.bluez.AudioSource and Connect() (operation timed out but the source is connected and pulseaudio manager see the new input interface).

    I’m not able to complete that. I don’t find any path where org.bluez.AudioSource is available.

    I tried with both a Nokia E65 phone and an Ubuntu 9.10 box as possible audio sources

  19. Pingback: Ubuntu Bluetooth entire Raiders - Desktop applications, Linux system administration, core studies, such as embedded systems and open source some of the basic classification - GNU/LINUX

  20. Nicolas Anquetil

    Hi,

    Worked for me on Lucid Lynx on a MacBook Pro 5,3
    Not really Plug-n-Play, but close enough.

    Any idea how to automatize step 5 (creating loopback between a2dp module and alsa module)?

    Currently I have to do it by hand 😦

  21. Hi Nicolas,

    which is your audio source device?
    could you please be so kind to post all the details? I mean all the commands, settings, etc you did to get the audio stream trsanfer work?

  22. Hi,
    I want to confirm the comments above on a2dp->frame_length assertion failed:
    I successfully streamed a2dp audio from nokia n900 mobile to ubuntu 10.04.
    Later, when I tried to use the same setup for nokia 5800 mobile I got the same frame_length error (I haven’t tried the fix).

  23. Is there any way of automating the whole procedure?

  24. Pingback: Setting up BlueZ with a passkey/PIN (to be used as headset for iPhone)

  25. Pingback: Streaming music to Ubuntu from a Bluetooth device « Mark Turner dot Net

  26. Pingback: Close, but not quite « Mark Turner dot Net

  27. megamanexent

    Anyone on Ubuntu 10.04 and would like an automated route, I made a script using Zenity to connect the audio source. Its on the Ubuntu Forums.
    This is the thread
    http://ubuntuforums.org/showthread.php?t=1464189
    This is the post whttp://ubuntuforums.org/showpost.php?p=9691711&postcount=24ith the script

  28. Pingback: 教程:Ubuntu 蓝牙Bluetooth使用全攻略-开源 -中文网络资讯快报 : CNSPOT.com

  29. Nicholas D. Wolfwood

    Here’s a little script to toggle connect/disconnect of a set bluetooth device to/from the default pulseaudio sink using the default bluetooth adapter:

    #!/bin/bash

    # Set this to your bluetooth device’s address
    BTADDRESS=”AA:BB:CC:DD:EE:FF”

    # Define a function for dbus-send
    bluez_dbus() {
    dbus-send –system –dest=org.bluez –type=method_call $@
    }

    # Ask pulseaudio for it’s default sink
    SINK=”$(pactl stat | sed -ne ‘/^Default Sink:/{s/^Default Sink:[[:space:]]*\([^[:space:]]\+\).*$/\1/;p}’)”

    # Ask bluez for it’s default adapter
    BTADAPTER=”$(bluez_dbus –print-reply / org.bluez.Manager.DefaultAdapter | sed -ne ‘/object path/{s/^[[:space:]]\+object path “\([^”]\+\)”.*$/\1/;p}’)”

    # Define bluez device
    BTDEVICE=”${BTADAPTER}/dev_${BTADDRESS//:/_}”

    # Ask if it’s connected yet
    CONNECTED=”$(bluez_dbus –print-reply ${BTDEVICE} org.bluez.Control.IsConnected | sed -ne ‘/^[[:space:]]*boolean/{s/^[[:space:]]*boolean \(true\|false\).*$/\1/;p}’)”

    if [ -n “${CONNECTED}” ]; then
    if [ “${CONNECTED}” = “false” ]; then
    # Connect bluez AudioSource
    bluez_dbus –print-reply ${BTDEVICE} org.bluez.AudioSource.Connect &>/dev/null

    # If we succeed go ahead and connect bluez AudioSource to pulseaudio sink
    if [ “${?}” -eq “0” ]; then
    pactl load-module module-loopback source=bluez_source.${BTADDRESS//:/_} sink=${SINK} &>/dev/null
    fi
    elif [ “${CONNECTED}” = “true” ]; then
    # Disconnect pulseaudio
    pactl unload-module “$(pactl list | sed -e ‘:a N’ -e ‘s/\n/$ /’ -e ‘ta’ | sed -e ‘s/[[:alpha:]]\+ #[0-9]\+/\n/g’ | sed -ne “/^Module #[0-9]\+.*Name: module-loopback.*source=bluez_source.${BTADDRESS//:/_}/{s/^Module #\([0-9]\+\).*$/\1/;p}”)”

    # Disconnect bluez AudioSource
    bluez_dbus ${BTDEVICE} org.bluez.AudioSource.Disconnect
    fi
    else
    exit 1
    fi

    exit 0

  30. Paco Soria had a problem with the HSP/HFGW profile assert. The problem lies in the call to hsp_process_push:

    if (u->profile == PROFILE_HSP || PROFILE_HFGW)

    The line needs another u->profile to work. We’re patching and testing it in MeeGo right now and will push upstream as soon as we’ve got it working.

  31. Pingback: Ubuntu 蓝牙全攻略  | Linux爱好者

  32. Pingback: Stream audio from phone over bluetooth to computer

  33. Hi,

    I’m having the same problem as Paco Soria, on meego 1.0.1. I get the following error when trying to load the module-loopback module:

    Dec 31 22:38:39 localhost pulseaudio[975]: module-bluetooth-device.c: Assertion ‘u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW’ failed at modules/bluetooth/module-bluetooth-device.c:1058, function hsp_process_push(). Aborting.

    I am using pulseaudio-0.9.21-15.3.i586.

    Any news on that, e8johan?

  34. It looks as if this was fixed in this patch, more specifically, around line 1000 in this file.

  35. Thanks e8johan, but the pulseaudio that is installed on my box (pulseaudio-0.9.21-15.3.i586.)already contains this patch.

  36. I’ve downloaded the source rpm of that package and located the issue. You can fix it by downloading the source rpm and then patching the line 215 of hfp_gateway_support.patch from:

    + if (u->profile == PROFILE_HSP || PROFILE_HFGW)

    to

    + if (u->profile == PROFILE_HSP || u->profile == PROFILE_HFGW)

    Then simply rebuild the package.

    If you want to discuss this further, please contact me directly. I’m e8johan and I use gmail.

  37. Sir i have n900 and x6 handfree a2dp i could not paired with n900 please help me i will be thankful to you for this great kindness

  38. Pingback: Configuring Linux as an A2DP Audio Sink « Computer/Electronics Workbench

  39. This worked great for streaming from my Motorola Milestone running Android 2.2 (CyanogenMod 6) to my Ubuntu 10.10 desktop or Debian Squeeze desktop. (Kudos for sharing this.)

    However, if I used my sister’s LG Optimus phone instead (also running Android 2.2), I suffered from the “Assertion '(size_t) decoded == a2dp->frame_length' failed” crash.

    I commented out the assertion in module-bluetooth-device.c which fixes the crash, but all I get is stuttering audio from the LG phone. So it sounds like the assertion crash is merely a symptom of another underlying problem.

    Is it more likely the problem lies in PulseAudio, or the upstream BlueZ layer? Or perhaps the phone itself?

  40. Joao Fernando

    Hi Joao (chara), do you know if it’s possible to connect a Source A2DP device without Pulse Audio ? Thanks.

  41. Hi João,
    I was trying to follow this step with Ubuntu 10.10/11.04 and it worked well with my phone running android 2.1. But surprisingly it did not, with my friend’s HTC Wildfire. ITo my curiosity, I just looked in to the log and it say

    pulseaudio[1569]: module-bluetooth-device.c: Assertion ‘(size_t) decoded == a2dp->frame_length’ failed at modules/bluetooth/module-bluetooth-device.c:1375, function a2dp_process_push(). Aborting.

    kernel: [150933.574257] indicator-sound[10304]: segfault at 8 ip 007a0599 sp bf8bac70 error 4 in libpulse.so.0.12.2[76e000+3f000]

    which felt like there is a handshake between A2DP control based on link quality , setting the framelength. But when it goes to pulseaudio to decode with the framesize, it throws an error.

    A bit of googling says https://tango.0pointer.de/pipermail/pulseaudio-discuss/2010-January/005994.html is what is happening

    The follow up mails confirmed my assumption, but I do not know what to do/

    Any pointers?

  42. Has anybody tried running it on an ARMV7 or arm.?
    I am running the bluez and pulseaudio on arm board, A2DP streaming disconnection happens after 5 seconds.

  43. You’re appropriate: search phrases without remarkable articles welcoming design, suggests almost nothing. I’m at the starting in Inbound Marketing and locate your report really quick and concise. Thanks!

  44. I tried following these instructions, but after calling org.bluez.AudioSource I get the following error:

    ‘org.bluez.Error.Failed: Stream setup failed’

    Anyone have ideas, what might be causing this?

  45. Another thing I was wondering was if it would be possible for bluez to provide a org.bluez.AudioSink.Connect() method on the laptop? That way I could connect to the laptop in similar manner as to any bluetooth headset.

  46. Hi,

    I have all theses stuffs working great, thanks for the explanations, very good job ;-). Also, I’have been googling since hours about automated things for the step 5, also took a look at the suggested links, but when I say “automated”, I mean automatically launch the load-module command when a bluetooth device is connected and not a script that I will have to manually launch each time I connect my phone.

    Any idea?

  47. I am very curious about what causes those disparities between different setups. I have tried to stream audio from several mobiles (1 iphone, 1 HTC Legend and one blackberry) to a belkin bluetooth dongle and all I get is stuttering sound for a few seconds and then pulseaudio crashes. But obviously from the comments here, there are some setups that work well. Looking at top, CPU usage is very low so it’s not the bottleneck for me. Where can the issue come from? bluez, pulseaudio, alsa, the bluetooth dongle, the bluetooth adapter on the phone? Does anyone know?

    Would be nice to know what to monitor in order to further investigate this 🙂

  48. Did the issue that was raised by Jeremy and Gireesan get resolved? I am having the same problem, also with an LG Optimus. It’d sure be nice to know if there’s a solution.

  49. It actually seems that a lot of issues were fixed lately since running Ubuntu 11.10 (beta) I can finally get lots of different configurations to work (from different phones to different bluetooth dongles on 3 differents machines) flawlessly. None of these configurations was working (stuttering sound) with 11.04. I would be interested to know which component fixed that: bluez, pulseaudio, the kernel, alsa?

    Anyway, that’s a really good news.

  50. Pingback: Audio streaming over Bluetooth | martin.zoller.tv

  51. romario satheesh

    hey it solved all ma problms……..

  52. 谢谢,成功了!

  53. Kal Torak

    Maybe Late,, But I have the same problem that elysion, some ideas ? ? ?

  54. Thanks now I’m on the intention to buy a phone LG Optimus LTE2
    This is my website http://www.androidmg.com he talks about the Android OS

  55. You can automatically connect your bluetooth device using module-switch-on-connect module for pulseaudio.

  56. Peter James

    Really good post, I managed to stream music from my pc (running ubuntu 21.04) to my andriod bluetooth handsfree sound box. However I did have problems as the blueman app would not launch while I was using Apple Mac OS X Lion theme, but now I dont use the themes blueman will open. Ive not yet figured out the automatic connection? Im currently removing the device from my paired list then re-pairing it and it works good.

  57. One small query regarding the implementation. I have managed to write a small Bluez based A2DP receiver client using this idea from Pulse Audio. I was successful upto the point of configuring the STREAM by sending BT_START_STREAM and BT_NEW_STREAM after BT_OPEN and BT_GET_CAPABILITIES message over the server socket. I got the streaming file descriptor and apparently the socket read returns 0 bytes when the stream is played on the remote device.

    I have made the socket properties Non-Blocking and Low delay. Any help regarding this issue is appreciated. Thanks in advance.

  58. Hello!

    I want to develop small computer for listening and recording music.
    I want my phone connect this computer as bluetooth headset (using A2DP
    protocol), but can’t do it.

    I huve succeed in connecting general headset to Linux but cant make
    Linux A2DP server.

    Can you please recommend me how can i do it without X11 utilities and
    without PulseAudio?

    Than’k you very much, in advance!

  59. on ubuntu 12.04 i just installed Bluetooth Manager, which has dependencies on BlueZ.
    then used it to make pairing with my phone, and bang! audio coming out my laptop speakers. very simple.
    hope its the same on all other setups…

  60. any one have this working in ubuntu 13.04?

  61. actually not, but i am working on it.

  62. Pingback: Can I use my computer as an A2DP receiver? | WyldePlayground.netWyldePlayground.net -

  63. Pingback: Can I use my computer as an A2DP receiver? | Ubuntu InfoUbuntu Info

  64. continuously i used to read smaller articles which also clear their motive, and that is also happening
    with this article which I am reading at this time.

  65. Which articles do you mean?

  66. Yeah could you share these articles with us?

  67. Ahaa, its pleasant dialogue concerning this post here at this weblog, I have read all that, so now me also commenting here.

  68. Wow! Great post! . I really appreciate your post. . I was searching that topic from few days its increase my knowledge.thanks a lot…….sell gift cards

  69. To conceive with the first line of my comment – I do alike to to present a large-scale thanks to the blog esteem. actually it is a gigantic work by him and I discovered out a high-quality help by his/her large minutia and numbers. I exactly crave to announced, delight stay it up your paid work. seldom I will assemble certain with you are posting and updating. Looking ahead to your more mails.

  70. Article writing is also a excitement, if you know after that you can write if not it
    is complicated to write.

  71. Pingback: Can I use my computer as an A2DP receiver? | CL-UAT

  72. Pingback: Can I use my computer as an A2DP receiver? - TecHub

  73. Pingback: How to get my bluetooth-enabled phone to pipe its audio through my Ubuntu machine? | Some Ubuntu Questions and Answers

  74. Pingback: Ubuntu:How to get my bluetooth-enabled phone to pipe its audio through my Ubuntu machine? – Ubuntu Linux Questions

  75. Pingback: Unix/Linux:complicated mpd/ssh setup howto? – Unix Questions

  76. Pingback: Ubuntu 蓝牙全攻略 | Linux学习

  77. This is the script that worked for my case (bose qc35 bluetooth headphones, ubuntu) :

    ###
    vi ~/headphones_connect.sh

    !/bin/bash
    sudo /etc/init.d/bluetooth restart
    pactl load-module module-loopback
    export BTADAPTER=`dbus-send –system –dest=org.bluez –print-reply / org.bluez.Manager.DefaultAdapter | grep path | sed ‘s/^.*”\(.*\)”.*$/\1/’`
    export DEVICE_PATH=`dbus-send –system –dest=org.bluez –print-reply $BTADAPTER org.bluez.Adapter.ListDevices | grep path | tail -n1 | cut -d'”‘ -f 2`
    dbus-send –print-reply –system –dest=org.bluez $DEVICE_PATH org.bluez.AudioSink.Connect

  78. Pingback: Android in the car – Impedance Mismatch

  79. Pingback: Use the Computer as an a2dp Receiver / Bluetooth Speaker in Ubuntu? - Stack All Flow

  80. Pingback: コンピューターをA2DPレシーバー/ Bluetoothスピーカーとして使用できますか? – Tutorial Bool

Leave a comment