Introduction: Enhance Raspberry Pi Media Center With Bluetooth A2DP (OSMC)

Picture of Enhance Raspberry Pi Media Center With Bluetooth A2DP (OSMC)

Having Bluetooth connectivity and enabling Raspberry Pi to behave as A2DP source is nothing new (see a general tutorial on Instructables), but the problem I had thus far was making that work on my media center Pi which was running Raspbmc. As I found out through numerous attempts to make it work, the problem was with Raspbmc suffering a bit too much from "weight loss" it forced upon itself, so the modules that work as expected on Raspbian were failing on Raspbmc:

$ pactl list sources short
Assertion 'l' failed at pulsecore/flist.c:168, function pa_flist_pop(). Aborting.Aborted

When I learned that Raspbmc was not going to be developed any longer and that its successor -- OSMC -- will be based on Debian distro that was not butchered to fit on 2 GB SD card, I immediately planned to give that a try :-)

What I found out when I started setting up A2DP on OSMC on my Raspberry Pi 2 is that OSMC is no longer based (as its predecessor was and as Raspbian is) on Debian Wheezy, but that it is based on Debian Jessie. That means bye-bye SysVinit and hello Systemd. And that change of service manager (making all "A2DP on Rasberry Pi" available tutorials obsolete or at least not easily replicable by novice users) is the real reason for this tutorial.

Step 1: Requirements

  • Raspberry Pi
  • 4GB+ SD card with installed OSMC (Release Candidate or newer)
  • Bluetooth v4.0+ USB adapter
  • a headphones or speaker system connected to 3.5 mm phones port
  • an Internet connection (for package updates)
  • either LAN connection for SSH or an USB keyboard

A note regarding the Bluetooth v4.0+ USB adapter:

Even though I've used IOGEAR GBU521, any similar adapter should sufice, but best check the verified/supported hardware list before buying!

Step 2: Log in to a Terminal

Boot the Pi.

1) Variant: Remote terminal (SSH)

If you've a LAN connection to the Pi, the easiest way to go through this tutorial is to use SSH -- they you can copy/paste commands instead of typing them :-)

Find what your Pis IP address is and SSH into it with your favorite telnet client.

2) Variant: Local terminal

In this case, connect your keyboard, go to Power menu in XBMC and choose Exit. XMBC will close in a few seconds, but will restart immediately again. To enter the terminal, make sure you press the ESC key after you've choosen the Exit and while the OSMC screen is still showing. That will stop XBMC from staring again ad you'll have a terminal prompt with login in front of you.

Either way, the default credentials for OSMC are:

Username: osmc
Password: osmc

Step 3: Install the Necessary Packages

Picture of Install the Necessary Packages

To get the state of repositories up-to-date, first execute:

sudo apt-get update

Optional: if you want, you can upgrade the outdated packages with:

sudo apt-get upgrade

Note: OSMC uses its own apt-get repository (http://apt.osmc.tv) for updating the system, which is a welcome change from Raspbmc, so not only does 'upgrade' upgrades the linux distro and installed 3rd party packages, it also upgrades the OSMC (media center and its packages).

After it finishes, execute this to install the necessary packages:

sudo apt-get install alsa-utils bluez bluez-tools pulseaudio-module-bluetooth python-gobject python-gobject-2

Image courtesy of: Keep Calm Network Ltd.

Step 4: Audio Configuration

Picture of Audio Configuration

Enable and load the sound module:

echo 'snd_bcm2835' | sudo tee -a /etc/modules
echo 'snd-bcm2835' | sudo tee -a /etc/modules
sudo modprobe snd_bcm2835 snd-bcm2835

Add users to pulse audio groups:

sudo usermod -a -G lp osmc
sudo usermod -a -G pulse-access,audio root sudo adduser osmc pulse-access

Heads-up: from this point forward, the tutorial uses GNU nano as terminal text editor, but you can easily use the one you prefer.

Open the configuration file for the PulseAudio daemon:

sudo nano /etc/pulse/daemon.conf

And find (press Ctrl+W, then type 'float') the line that reads:

resample-method = speex-float-1

and change it so:

; resample-method = speex-float-1
resample-method = trivial

Because we'll be running PulseAudio deamon in system mode, loading additional modules will not be possible once the deamon is started, so we need to configure their inclusion in the PulseAudio startup script for system mode:

sudo nano /etc/pulse/system.pa

and add the following lines (which check for existance and enable various modules):

.ifexists module-bluetooth-policy.so
load-module module-bluetooth-policy
.endif
.ifexists module-bluetooth-discover.so
load-module module-bluetooth-discover
.endif
.ifexists module-bluez5-device.so
load-module module-bluez5-device
.endif
.ifexists module-bluez5-discover.so
load-module module-bluez5-discover
.endif

We also need to create the service starting script:

sudo nano /etc/systemd/system/pulseaudio.service

and edit it like so:

[Unit]
Description=Pulse Audio
[Service]
Type=simple
ExecStart=/usr/bin/pulseaudio --system --disallow-exit --disallow-module-loading --disable-shm --daemonize
[Install]
WantedBy=multi-user.target

Execute these two commands to scan for new/changed units and to restart the PulseAudio service:

sudo systemctl daemon-reload
sudo systemctl enable pulseaudio.service
sudo systemctl start pulseaudio.service

All that is left to do for audio is to enable output to a prefered connector (0=auto,1=headphones,2=hdmi):

amixer cset numid=3 1

and, as volume will be controlled by the client, to set the volume level on the server side to 100 percent:

amixer set Master 100%
pacmd set-sink-volume 0 65535

Step 5: Bluetooth Configuration

Picture of Bluetooth Configuration

To make sure A2DP audio sinks are allowed, open the config file:

sudo nano /etc/bluetooth/audio.conf

and place these three lines under [General] heading:

[General]
Enable=Source,Sink,Media,Socket
HFP=true
Class=0x20041C

Next, open another config file:

sudo nano /etc/bluetooth/main.conf

and place these lines under [General] heading:

[General]
Name = osmc
Class = 0x20041C

Next, list the BT adapter config:

sudo hciconfig -a

and note the MAC address (in form of XX:XX:XX:XX:XX:XX). You will need to specify it here:

sudo nano /var/lib/bluetooth/XX:XX:XX:XX:XX:XX/settings

where you should paste these lines:

[General]
Discoverable=true
Alias=osmc
Class=0x20041C

Bring up the BT:

connmanctl enable bluetooth
sudo hciconfig hci0 up

and in the BT control shell:

bluetoothctl

Then, execute the following commands to enable the agent and start the scan:

agent on
default-agent
discoverable on
scan on

That should display a list of visible BT clients (if not, execute 'devices' command). Next, execute the following to pair/trust your client device(s):

pair XX:XX:XX:XX:XX:XX
Request confirmation
[agent] Confirm passkey 503116 (yes/no): yes
trust XX:XX:XX:XX:XX:XX

Note: repeat the pair & trust commands for each device you want to allow to connect.

With this the Bluetooth part of the configuration is done.

Step 6: Fix for Automatic Audio After Reboot

When the past steps in the tutorial are all done, we can immediately see the effect -- the client and the Pi are connected and the client can stream audio via BT.

Woohoo! That's it!...Or, is it?

The problem comes when the Pi is restarted. Then, until someone is logged into console, PulseAudio will not work.

One solution is to enable auto-login into console.

sudo cp /lib/systemd/system/getty@.service /etc/systemd/system/autologin@.service

Next, we symlink that autologin@.service to the getty service for the tty on which we want to autologin, for example for tty1:

sudo mkdir /etc/systemd/system/getty.target.wants
sudo ln -s /etc/systemd/system/autologin@.service /etc/systemd/system/getty.target.wants/getty@tty1.service

Up to now, this is still the same as the usual getty@.service file, but the most important part is to modify the autologin@.service to actually log you in automatically. To do that, you only need to change the ExecStart line to read:

ExecStart=-/sbin/agetty -a osmc %I 38400

That's it. After this you'll briefly see the login prompt when the OSMC boots up, but it will allow PulseAudio to run even without you logged in.

reboot

Source: http://unix.stackexchange.com/a/42362

Step 7: Conclusion and Tips

My main goal was to reuse the always-on devices (media centar Raspberry Pi and Android phones/tablets) to stream online subscription music (namely Google Play Music) without needing to have PC turned on or the client device jacked in.

Naturally, the setup can be used to stream all sorts of audio through Pi. For example, gaming on tablet sounds pretty sweet when played on home stereo :)

Tip:

  • What I encountered occasionally on the phone was that sometimes it doesn't automatically reconnect to the Pi and that, when Pi (osmc) is pressed in BT phone settings, it immediately disconnects. The solution for this seems to be to turn BT on the phone off and then back on. After that (BT "reset") the phone again automatically connects to the Pi.

Nota bene:

  • I was writing down each step I applied while I was investigating how goal in this tutorial can be achieved, but when I started to verify the tutorial (on a clean OSMC install) some weeks later, the version of the OSMC was incremented and I didn't manage to reproduce it exactly step by step, so if you find some parts are off, feel free to suggest improvements in the comments (and I will hopefully update the tutorial).

Principal source of information: ArchLinux Wiki.

Honorable mention: inspired by a tutorial from dantheman_213.

Comments

pubbb (author)2015-07-22

Hello,

I'd like to thank you for this guide. It is really straight forward and it worked great for me.

Now I want to share something I added, which will allow your friends to be able to pair and play music too, without having to configure anything on your PI.

First you have to download the bluez source code and untar it.

Then you have to modify bluez/test/simple-agent file replacing the following section:

nano /usr/src/bluez-5.23/test/simple-agent

def RequestPinCode(self, device):

print("RequestPinCode (%s)" % (device))

set_trusted(device)

return “1234"

Then I created a script to switch to discoverable mode, disable secure simple pairing and finally start this agent.

nano /usr/bin/btscript.sh

#!/bin/sh

result=`ps aux | grep -i "simple-agent" | grep -v "grep" | wc -l`

if [ $result -ge 0 ];

then

sudo hciconfig hci0 piscan

sudo hciconfig hci0 sspmode 0

sudo /usr/bin/python /usr/src/bluez-5.23/test/simple-agent &

else

echo "BT Agent already started"

fi

Finally to start the script on autologon:

chmod +x /usr/bin/btscript.sh

nano /etc/rc.local

#!/bin/sh -e

#

# rc.local

#

# This script is executed at the end of each multiuser runlevel.

# Make sure that the script will "exit 0" on success or any other

# value on error.

#

# In order to enable or disable this script just change the execution

# bits.

#

# By default this script does nothing.

/usr/bin/btscript.sh

exit 0

Now just reboot and that’s it! You will be able to pair and play music from any bluetooth devices using the code PIN you defined in your agent (here “1234”).

Source: http://www.linuxquestions.org/questions/linux-wireless-networking-41/setting-up-bluez-with-a-passkey-pin-to-be-used-as-headset-for-iphone-816003/

anmorfe (author)pubbb2015-10-26

Hello, I have tried to do this, but I can't find /usr/src/bluez-5.23/test/simple-agent

RobertS23 (author)anmorfe2015-10-27

@anmorfe: possibly you skipped this step:

First you have to download the bluez source code and untar it.

So, something like this should work for you:

wget http://www.kernel.org/pub/linux/bluetooth/bluez-5.35.tar.xz

tar xf bluez-5.35.tar.xz

cd bluez-5.35

TimL64 (author)RobertS232016-02-07

I had somewhat mixed feelings about mixing versions, so preferred to download the sources of the version that was also installed via apt-get:

1. If the line "deb-src ..." starts with a # (is a comment) remove the #. If it's not commented out, continue with 3

2. sudo apt-get update

3. cd /usr/src

4. sudo apt-get source bluez

This was the only missing part of pubbb's addition.

Thank you Robert and pubbb for your description, it's literally the only one out there for jessie-based distros.

TimL64 (author)TimL642016-09-02

Forgot to mention:

Step 0: Open apt sources file: sudo nano /etc/apt/sources.list

RobertS23 (author)pubbb2015-07-22

Nice enhancement :)

Thanks!

fury0 (author)2015-05-06

Thank you for sharing this informations. And made it and ... it works!!!

As I use a Hifi Digi+ sound card, I did not make the first 2 parts of step 4, also did not type the command

# amixer cset numid=3 1

# amixer set Master 100%

# pacmd set-sink-volume 0 6553

Also I do not need the 6th step (OSMC RC2).

Thank you again.

RobertS23 (author)fury02015-05-06

Thanks for confirming :)

Much appreciated!

scoobydrvr (author)2016-08-11

Okay, I've tried my best to blend together both the instructions above and the suggestions below and still cannot get any audio output.

I'm using a R Pi 1 Model B while I wait for a dedicated model 3 to arrive with the OSCM July 1st image. I'm starting to wonder if something has changed in the bluetooth architecture because the folder '/etc/bluetooth' is not there and the file 'main.conf' does not exist either. I went ahead and did a 'mkdir /etc/bluetooth' and created the main.conf file with the contents suggested but that doesn't seem to have fixed the issue.

I've also tried changing the Audio Out settings in OSMC and none of them will produce the bluetooth audio either...

Does anyone have any ideas?

TorstenW2 (author)scoobydrvr2016-11-23

Hi together,

I have exact the same problem with my Pi 1 Model B.

I use a fresh OSMC installation and I followed the instructions step by step, till I have to add something to the folder /etc/bluethooth. This folder does not exist.

Is this only a problem of Pi 1?

Torsten

OrenK2 (author)2016-11-10

Hello Robert,

Thanks for the great instructions. Went through them step by step and everything works! Now.. I'm interested in another addition which I think might be very much welcome by other users as well - have the BT connect event trigger an HDMI CEC message to the connected AVR / TV and get it to turn on...

My existing RPi2 + OSMC does exactly that when turned on (including AVR input change) but when I connect to its BT from a client and stream audio it doesn't..

Any thoughts on how to achieve that?

Thanks again!

O,

RobertS23 (author)OrenK22016-11-10

Thanks.

No idea how to do that, but seems it could be interresting for others, too. Maybe when you succeed you can post a followup.

karpate (author)2016-10-08

Hi,

I tried to install my bluetooth adapter according to the intstruction but failed.

Now
my oscm installation is not starting anymore. I have still access to
console. hope someone can help me in checking the logs below what is
happening, thus I am not that experienced with unix...

http://paste.osmc.io/baquyicuwi

http://paste.osmc.io/tohacacexe

greets ingo

BakGatN (author)2016-07-04

what FANTASTIC work!

well done, sir.

I hope this gets pulled upstream into OSMC or OpenELEC for native support

DRPD (author)2016-07-02

I have installed but sound from my bluetooth speaker last only for 10 sec then no sound. My speakers still connected but no sound after 5-10 sec.

How do I get continues sound?

Thanks

DRPD (author)2016-07-02

I have successfully installed on my OSMC and I can hear the sound from my Bluetooth speaker but it is only for 10 sec and then no sound.

Also, I noticed that when I play You tube video, I can hear the sound with video.

Any idea?

alvarosancho (author)2016-05-13

I thought that enabling Raspberry Pi as A2DP source means to send data to be played on an A2DP sink such a bluetooth headset or speakers. But step 1 says I must connect headphones or speakers to the 3.5mm port. What is this tutorial for?

CedM (author)2016-04-22

Thank you very much for your guide.

It work great for me, I just need to set pulse audio in OSMC audio parameter instead of HDMI.

Thank you very much one more time.

Bye.

steelsoldat (author)2015-06-18

Thanks for the tutorial!

For me it worked when reverting from RC3 to RC, but after restarting the device(pi) is not detected as a ad2p speaker but rather a normal Bluetooth device(with no label). When tryign to connect to it the connection would drop after less than a second.

I believe it may be the ad2p configs are not taking effect, but am unsure as I followed the guide exactly.

MarcelH10 (author)steelsoldat2016-01-07

Hi, I am having the same problem. It used to work fine for a couple of days, then when the pi rebooted, my bluetooth device is now Class 0x00041C and cannot be connected to anymore.

The file /var/lib/bluetooth/XX:XX:XX:XX:XX/settings seems to get overwritten at boottime where the line Class = 0x20041C gets erased.
I can manually set the device class back to 0x20041C using
"hciconfig hci0 class 0x20041C" but I have to do this after every reboot.

Any suggestion on where to fix this?

ChrisT180 (author)MarcelH102016-04-13

"Hi, I am having the same problem. It used to work fine for a couple of days, then when the pi rebooted, my bluetooth device is now Class 0x00041C and cannot be connected to anymore.

The file /var/lib/bluetooth/XX:XX:XX:XX:XX/settings seems to get overwritten at boottime where the line Class = 0x20041C gets erased.
I can manually set the device class back to 0x20041C using
"hciconfig hci0 class 0x20041C" but I have to do this after every reboot.

Any suggestion on where to fix this?"

SAME HERE, seems that the Class Settings and the Device name are saved somewhere else than /etc/bluetooth/main.cfg or /var/lib/bluetooth/XX:XX:XX:XX:XX/settings

there seems to be some storage for default values nobody knows about ^^

ChrisT180 (author)ChrisT1802016-04-13

where does hciconfig write it's Settings? and another interesting fact, if i manually set via "hciconfig hci0 class xxxxx" and do "hciconfig -a" i still geht the old class, when i start bluetoothctl, and run "show" i get the updated class "xxxxxx" from my manual setting WEIRD

BaReinhard (author)2016-03-21

This was great! I was lazy and skipped to step 10, and it was amazing. Works great, I'm running on a 5-5-15 wheezy Distro in berry boot for a fun little car project. The only issue is that when I turn on the power it becomes discoverable and I have to manually click connect for the Bluetooth to start. Is there anyway to get it to automatically pair with my iPhone as soon as it gets booted?

BaReinhard (author)BaReinhard2016-03-21

I have found adding the command
sudo rfcomm connect 0 MAC address 1
To the end of my /etc/rc.local works for auto pairing but it causes issues with my shutdown script with the car switch from mausberry circuits.com

MatthewL91 (author)2016-03-19

Hello! There is an awesome add on that jgauthier made

http://engineeringdiy.freeforums.org/software-blue...

I was able to get it all connected, except the sound does not work!! can anyone please help me? I'm using the RPI2, have the correct bluetooth adapter, and can't figure out why the bluetooth audio won't play.

AledH (author)2016-03-17

Hi, great tutorial. Was working until I rebooted the device. Anybody have any ideas?

Thanks.

AlexanderS92 (author)2016-01-14

Thanks for this guide.
With the current OSMC Version i had to change a few steps.

1. Instead of modprobe add the following line to your config.txt
dtparam=audio=on

2. The file /etc/bluetooth/audio.conf doesn't exist anymore. I added
Enable=Source,Sink,Media,Socket
HFP=true
Class=0x20041C
to the /etc/bluetooth/main.conf file.

dognmonkey (author)AlexanderS922016-03-07

This one works for me too... no sound on both HDMI and Composite audio

Thanks,

korange2 (author)AlexanderS922016-02-19

I encountered the issue of no audio and this resolved my issue for me. Thanks

MustafaK32 (author)AlexanderS922016-02-09

I am also no longer getting audio after updating OSMC on RPi. I tried your steps but it didn't solve the issue. Did you guys do anything else? I am on 15.2 on RPi.

MaximeB20 (author)AlexanderS922016-01-27

awesome tutorial and update for current OSMC version too.

Indeed, with just the tutorial all went fine but i had no sound.

with these 2 steps I've got sound from hdmi !!! (I was so happy)

But another problem appears : many very short mute (less than 1 sec) comes every 20 sec...

Someone has an idea ? even if it is a very cool stuff it's not usable like this...

many thanks

HenrikK2 (author)MaximeB202016-02-01

I saw this on another guide:
Output audio after 20 seconds stopped

Edit daemon configuration:

sudo nano /etc/pulse/daemon.conf

Change

; exit-idle-time 20

to

exit-idle-time -1

MaximeB20 (author)HenrikK22016-02-08

Hi, I've just tried but it doesn't work...

it worst than before... mute every 5 sec

I'll try another tuto later

thank for your time

Best,

MaximeB20 (author)HenrikK22016-02-02

Hi HenrikK2,

Thank you for your answer, I'll try this evening !

I keep you informed.

best,

got it to work but how to change to headphone output instad of hdmi?

SteffenK5 (author)AlexanderS922016-01-26

Hey AlexanderS92,

thank you very much for this info! Worked grad for me with a Raspberry Pi 2 and OSMC 15.

dognmonkey (author)2016-03-07

Hello Robert, I finally got the bluetooth to work with my OSMC on Raspberry Pi 2. The sound didn't work until follow AlexanderS92 trick. The amazing thing is the sound works on both HDMI and Composite audio with the same numid=3 1.

Thanks all

georg_mysicka (author)2016-02-28

Hi guys,

please, could somebody try to advise what's wrong if I got after:

sudo systemctl enable pulseaudio.service

"Failed to execute operation: Bad message" ???

pulse.audio text file is exactly the same like here, I've just copy and paste it and add rows as is pictured here using enter...

Thank you

Sndstrm (author)2016-02-27

Thanx!

I've been trying out different tutorials and this is the only one that really worked without any problems! :)

Sndstrm (author)2016-02-27

Thanx!

I've been trying out different tutorials and this is the only one that really worked without any problems! :)

AnuS14 (author)2016-02-24

Thanks Robert,

for excellent instructions.

I was able to get it work on RPi 2B connected to Amp via HDMI, but most of time audio volume oscillates (fades and slowly comes back). Any idea why ?

TerryW50 (author)2016-02-06

Hello,

Great tutorial. I'm a total noob so this helped immensely. My only problem is when I reboot, I can' get any audio out via hdmi or analog. I made sure to set the output of my pi2 as auto because I will be implementing this in my car as a custom made head unit. Any advice on how to get this bluetooth connectivity working so that the Pi2 will output the music or youtube videos from my phone?

Thanks,

Terry

ZippyTs (author)2016-01-15

Got this to work just fine under raspbian jessie with no issues. Just had to make a few tweaks here and there to match up to my install. Thanks my CarPi is coming along nicely now! Thanks

RafaG4 (author)2016-01-01

Hi thanks for the tutorial.

I have a question.

You can play the sound at the same time analog and bluetooth?

You can install paprefs in OSMC?

Sorry for my English.

Thank you.

IljaS1 (author)2015-12-09

Hey! Pretty great guide. I have a following issue/task. I have audio source 1, I splice RPi with this setup into it's output. I need it to switch relays over from Source 1 to RPi audio output once a bluetooth device is connected to RPi. Is there a ready solution to do this or may be someone is willing to help?

IljaS1 (author)2015-12-09

Hey! Pretty great guide. I have a following issue/task. I have audio source 1, I splice RPi with this setup into it's output. I need it to switch relays over from Source 1 to RPi audio output once a bluetooth device is connected to RPi. Is there a ready solution to do this or may be someone is willing to help?

NamkingWIN (author)2015-11-23

With the last version of OSMC (at this time). I've just finished step 3 then rebooted and setup in OSMC:

1. System-->Setting-->System-->Audio out--> Choose ASA...

2. System-->OSMC-->Network-->Bluetooth-->Pair with your Bluetooth speaker

3. Done.

Have fun!

zhoug (author)2015-11-10

Hello,

thanks a lot. I've followed your guide and now I can play music via bluetooth from my phone. But one Problem I still have is that I could not control the volume via phone while playing music.

I've run this two command successfully.

$amixer set Master 100%

Capabilities: pvolume pswitch pswitch-joined

Playback channels: Front Left - Front Right

Limits: Playback 0 - 65536

Mono:

Front Left: Playback 65536 [100%] [on]

Front Right: Playback 65536 [100%] [on]

$pacmd set-sink-volume 0 65535

additional information:

osmc@osmc:~$ pactl list sources short

0 alsa_output.0.analog-stereo.monitor module-alsa-card.c s16le 2ch 44100Hz SUSPENDED

osmc@osmc:~$ pactl list sinks short

0 alsa_output.0.analog-stereo module-alsa-card.c s16le 2ch 44100Hz SUSPENDED

Could you please give some tips?

Thanks a again

grahamniall (author)2015-10-26

Nice tutorial, works like a charm, thanks! I've been wondering about the quality though. I've fiddled around with some of the settings for Pulseaudio (http://manpages.ubuntu.com/manpages/hardy/man5/pulse-daemon.conf.5.html) but it still seems to be not excellent. So 2 questions: Any way how I can monitor the current quality (bitrate)? Also, I'm wondering if the sound get's sent on digitally if I use my phone to send music to the Pi and then through HDMI to an amplifier? Or does the bluetooth intially resample the music?

Zwompf (author)2015-10-22

Hallo,

thanks for the turorial. Everything works and i can play music over my ipad.

But the last line of the tutorial doesn't work on my Pi.

osmc@osmc:~$ ExecStart=-/sbin/agetty -a osmc %I 38400
-bash: -a: command not found

Please can anybody help me.

Thanks