Instructables

Turn your Raspberry Pi into a Wireless Portable Bluetooth Audio System A2DP

Picture of Turn your Raspberry Pi into a Wireless Portable Bluetooth Audio System A2DP
Howdy folks! I had the idea of turning my Raspberry Pi into something like the Beats By Dre portable audio system found here:
http://www.beatsbydre.com/speakers/beatbox-portable-usb/beatbox-portable-usb,default,pd.html

It’s a cool product, don’t get me wrong, but I’m not really down to pay $400+ tax for some fancy looking speakers (which don't even give you rechargeable batteries, by the way). So I decided to set off to replicate the functionality without the hefty price tag.

OBJECTIVE: To create a Raspberry Pi that automatically boots into the command line and becomes discoverable via Bluetooth. Any Bluetooth-enabled device with the A2DP (Advanced Audio Distribution Profile) support will be able to push audio to the Pi through its Analog (default) or HDMI speaker output. When a Bluetooth device connects, the PI routes the connection through to Pulse audio and Bluetooth discoverability is turned off. The audio should play seamlessly from here. You can then disconnect your device (likely a smartphone) and the PI will become discoverable again via Bluetooth and another device is free to connect. The default pass key will be 0000 but most devices input this automatically so it should be hassle free!

NOTE: I did find that a lot of other people in the Linux community have attempted to do the same thing to their PI but not as successfully as I have! My setup allows the device to run headless (without a monitor) from boot and any Bluetooth device can connect and disconnect without an issue. I’ve seen a lot of other people with tutorials that make you login via command line first or login to the desktop and setup the Bluetooth connection manually. LAME! The goal of this is to be as similar to a *product* as possible. :) enjoy!

NOTE: This tutorial assumes you have a fair amount of Linux/command-line knowledge. I won’t be explaining basic commands or ideology so if this is above your head find a friend!

What is the Raspberry PI?
The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. --Raspberry PI website

You can learn more about the PI and how to get one, here:
http://www.raspberrypi.org/

Requirements
• Raspberry Pi
• Bluetooth v4.0+ micro USB dongle
• 4GB SD Card

Requirements for [portable audio]
• Battery-powered speaker(s)
• Battery pack for Raspberry Pi
• Enclosure to keep everything in
 
Remove these adsRemove these ads by Signing Up
1-40 of 178Next »
MateuszK33 days ago

Hi, everything works like a charm.

But I have a problem with pairing. I'm connecting my tablet(android), laptop(win7), phone(android) to Pi, but everything works As long as I connect for the first time. When devices are paired, and i reconnect to the PI then the script /usr/lib/udev/bluetooth doesn't start.

I checked syslog if there is an event for "ADD" when connecting my paired device to Pi but there is no such event going from KERNEL - so the line:

KERNEL=="input[0-9]*", RUN+=/usr/lib/udev/bluetooth from /etc/udev/rules.d/99-input.rules doesn't get triggered.

For the first time (connecting not-paired) the line in syslog which triggers script is:

syslog:

Jan 26 19:00:39 raspberrypi kernel: [ 856.520658] input: XX:XX:XX:XX:XX:XX as /devices/virtual/input/input0

then i can see output in

/var/log/bluetooth_dev

Mon Jan 26 19:00:39 UTC 2015 : Executing bluetooth script...|add|
Mon Jan 26 19:00:41 UTC 2015 : Setting bluez_source to: bluez_source.XX_XX_XX_XX_XX_XX
pactl load-module module-loopback source=bluez_source.XX_XX_XX_XX_XX_XX sink=alsa_output.platform-bcm2835_AUD0.0.analog-stereo rate=44100 adjust_time=0
24

For the second time (paired)

syslog:

Jan 26 19:01:05 raspberrypi bluetoothd[2008]: Discover: Connection timed out (110)

and nothing happens.

But i can ping the phone from PI (l2ping) so the connection is established?

To be honest constantly unpairing the devices is painful ;)

how can i improve this? i looked for the answers about 110 error but what I found is not relevant in my opinion.

any help?

dtb065 days ago

Hi, it is working fine with sideeffekt's script. I'm using it in my car to play music with a Lumia 735, but I also use an USB sound card instead of the raspberry integrated port, which has also an input jack.

I was wondering : do you think it is possible to change the device class to be recognized as a music+voice device and use it with a microphone plugged in order to answer calls or use voice guidance or to send SMS with voice recognition ? Do I need someting else like an activation button ?

Thanks to everybody for their input (and sorry for my Englidh, I'm French).

guaycuru6 days ago

After a firmware upgrade (rpi-update) I stopped getting audio after connecting.
After some digging around, I found that I had to make this change on /usr/lib/udev/bluetooth :

Replace this line:

AUDIOSINK="alsa_output.platform-bcm2835_AUD0.0.analog-stereo"

With this:

AUDIOSINK="alsa_output.0.analog-stereo"

Hope this helps someone else!

Forgot to mention: great tutorial, thank you very much!

RobertS236 days ago

I can connect and my device is playing to Pi, but I have no sound.

When I check this I get:

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

Its working great but i have a question. Whats about the sound if i get a call?

The voice comes out of the phone and for me its interesting to hear it out of the 3,5mm jack of the Pi because it will be mountet in my car and i like to talk free hands. Have anyone an idea?

regrats from Germany

please excuse my English

Robert__S1 month ago

The bluetooth script at (what should be) /lib/udev/bluetooth executes when a USB dongle is inserted or removed - which is not the desired action. I suggest adding the following near the top of the script - so that the script only executes if a bluetooth device links with the Raspberry Pi:

DEVTYPE=$(expr "$DEVTYPE" : "\([a-zA-Z]\+\).*")
[ "$DEVTYPE" != "link" ] && { echo "DEVTYPE is $DEVTYPE - exiting" | logger; exit; }

One small issue I am having is that I have lost a lot of bass to what I would normally have (streaming from Spotify to BT as compared to having headphones in). Do you know if this is something I can address or is this just the nature of Bluetooth or the Pi?

This worked great! The only issue I had was the volume being very low. I found a link http://kmonkey711.blogspot.co.uk/ which mentions running this command

pacmd set-sink-volume 0 65537

Cool stuff :) On to an FM transmitter now!

ThrRokstar1 month ago
How would you get this to work with the model b+?
sobodash1 month ago

Made this and it's working great except for one problem. I have a Macbook Pro that recognizes the Pi as an audio devices, connects fine and switches to Bluetooth audio.

However, the Mac's audio does not appear to actually be streaming to the Pi. There is simply no sound at all. I tried toggling back and forth between the internal speakers and the Bluetooth Pi, but there was no real change.

Anyone have an ideas about what might be going on? I'm running Yosemite if it's relevant.

Hi, i have the same problem. Pairing with Iphone works very well. Connecting and pairing with my Macbook works but I can´t hear any music I play. Is there a solution to overcome this problem?

AndreaB31 month ago

Hi, many thanks for this tutorial.
I tried it on raspian wheezy 9/9/2014 (fresh install) and I'm stuck. My phone (android 4.2.2) shows the Pi as paired and connected to media audio, but I can't actually ear any output.
I looked around the internet and to try the connection I run

sudo l2ping <address>
but the raspberry said

Cannot connect: invalid exchange
I read all the comments here and didn't find a possible workaround.

Did someone manage to get this work with a recente realese of wheezy?

schmo901 year ago
after weeks of madness and no succes i got it finally working but with a complette different start script because the even kernel event did not work for me.

at first i decommended in the
sudo nano /etc/bluetooth/audio.conf
HFP=true

after that i made a script

sudo nano /EnableBTMusicStream.sh

to get my bluetooth device mac adress

#!/bin/bash
running=1
while [ 1 -lt 10 ]; do
  source=$(pactl list short sources |  grep -o "bluez.source.\(.*\)module" | sed 's/'\module'/''/g' |  sed 's/[ \t]*$//')
    if [ "$source" ]; then
      if [ $running -eq 1 ]; then
        sudo -u pi pactl load-module module-loopback source=$source sink=alsa_output.platform-bcm2835_AUD0.0.analog-stereo
        running=2
      fi
   else
     sudo hciconfig hci0 piscan
     running=1
  fi
  sleep 5
done


 than

sudo nano /etc/init.d/EnableBTMusic


#! /bin/sh
# /etc/init.d/blah
#

# Alles, was in jedem Fall ausgeführt werden soll, steht am Anfang
touch /var/lock/somefile.lock

# Bestimmte Funktionen werden per switch-case Anweisung geregelt
case "$1" in
  start)
    echo "Starte Beispielprogramm "
  sudo -u pi sh /EnableBTMusicStream.sh &
    ;;
  stop)
    echo "Stoppe Beispielprogramm"
    # ./starte_mich.sh --stop
    ;;
  *)
    echo "Usage: /etc/init.d/starscript.sh {start|stop}"
    exit 1
    ;;
esac

exit 0



 sudo chmod 755 /etc/init.d/EnableBTMusic
sudo update-rc.d EnableBTMusic defaults

with this changes i can hear music on my raspberry :-)
i hope i could help someone with that infos...

Hi, thanks for posting this.
I have the same issue you had, so, my phone says the devices are paired but no sound is actualli reaching the 3.5 mm jack.
I'm trying to get it to work using a 9/9/2014 wheezy, but I read in the comments that many people suggest to use a older kernel. Did your script work with a recent realese of raspian? I so I'll give it a try.

rpotee schmo901 year ago
For some reason, I need to ssh into my RPi to get this solution to work. Any work arounds? I have all of the configuration detailed for this project, plus your solution.
derekkg rpotee1 year ago
Me too! If I have Ethernet plugged into my pi, it works. If I don't, I can't connect. Did you ever figure out what the problem was?
rpotee derekkg1 year ago
I caved in and followed these instructions to install shairplay on my raspberrypi. Now, I can play music from my rooted Android tablet and iTunes over wifi, and it's much more reliable.

http://arstechnica.com/information-technology/2013/04/airplaying-music-and-video-from-ipad-to-raspberry-pi-its-as-easy-as/
rpotee schmo901 year ago
This resolved my issue! But the volume was weak, so I added
amixer sset Master 100%
to the end of/EnableBTMusicStream.sh
jaime41 month ago

Hello had good luck following your tutorial, everything works great only issue i have is volume is why too low, I've tried playing with the master volume and the sink threshold values in the sudo nano /usr/lib/udev/bluetooth with no changes. any ideas?

ron.laws861 month ago

/usr/lib/udev/bluetooth does not exist...

sideeffekt9 months ago

I had issues with the udev section, my device was not showing up as an input device from udevadm monitor. So I had to change /etc/udev/rules.d/99-input.rules to correctly function when the device wasn't showing up as an input. Hopefully this will be helpful is anyone else comes across the same issue. I changed it to:

KERNEL=="hci0:12", SUBSYSTEM=="bluetooth", RUN+="/usr/lib/udev/bluetooth"
KERNEL=="hci0:11", SUBSYSTEM=="bluetooth", RUN+="/usr/lib/udev/bluetooth"
KERNEL=="hci0:13", SUBSYSTEM=="bluetooth", RUN+-"/usr/lib/udev/bluetooth"

This now covers the different ways my device is identified when it connects. It is almost always one of the devices above.

Then to get the /usr/lib/udev/bluetooth script to work I had to go through and completely piece together a new one that autopopulated the appropriate sink and source sections without relying on /sys/devices/virtual/input/ so my bluetooth script looks like this:

#!/bin/bash

#Set User to run portions of the script as
BUSER=pi

# Turn off BT discover mode before connecting BT to audio
hciconfig hci0 noscan

#Set Volume
sudo -u "$BUSER" amixer set Master 100%

#Set Sink Volume
sudo -u "$BUSER" pacmd << !
set-sink-volume 0 65537
!

#Log add/remove status
echo "Executing bluetooth script...|$ACTION|" >> /var/log/bluetooth_dev

#Create audio sink variable as udev su/translated to user $BUSER for pactl command then script to log

BSINK=$(sudo -u "$BUSER" pactl list sinks short | tail -n 1 | awk '{print $2;}')

echo BSINK=$(sudo -u "$BUSER" pactl list sinks short | tail -n 1 | awk '{print $2;}') >> /var/log/bluetooth_dev

#Create buetooth source variable as udev su/translated to user $BUSER for pactl command then script to log

BSOURCE=$(sudo -u "$BUSER" pactl list sources short | grep bluez | awk '{print $2;}')

echo BSOURCE=$(sudo -u "$BUSER" pactl list sources short | grep bluez | awk '{print $2;}') >> /var/log/bluetooth_dev

#Run final pactl command as user $BUSER, then plug in variables, and finally write command to log file
sudo -u "$BUSER" pactl load-module module-loopback source="$BSOURCE" sink="$BSINK" rate=44100 adjust_time=0

echo sudo -u "$BUSER" pactl load-module module-loopback source="$BSOURCE" sink="$BSINK" rate=44100 adjust_time=0 >> /var/log/bluetooth_dev

# Turn on bluetooth discovery on disconnect
if [ "$ACTION" = "remove" ]
then
sudo hciconfig hci0 piscan
fi

Thank you! The rewrite did the trick. So for everyone wondering how to get this working:

Get the image from Zonx, The one from 2 september 2013. then the following things right as the pi is booted up:

1. sudo apt-get update (never never never ever apt-get upgrade)

2. sudo apt-get install rpi-update

3. sudo BRANCH=next rpi-update

4. Then follow the instructions as normal

5. At the step 5 with the udev part add these extra things from sideeffekt:

KERNEL=="hci0:12", SUBSYSTEM=="bluetooth", RUN+="/usr/lib/udev/bluetooth"
KERNEL=="hci0:11", SUBSYSTEM=="bluetooth", RUN+="/usr/lib/udev/bluetooth"
KERNEL=="hci0:13", SUBSYSTEM=="bluetooth", RUN+-"/usr/lib/udev/bluetooth"

6. get the new script from sideeffekt.

With the original script i could connect but no sound, and with the new image from January this year I've had the famous 3 second sound bug en PI 'bluescreens'

Also, get a good bluetooth 4.0 dongle, just in case.

Big thanks to Dantheman, Zonx and Sideeffekt!

hey guys,

since i added the 3 new KERNEL-lines I'm able to connect to my raspy. Unfortunately I didn't get any sounds automaticaly due to the scripts. The debug tells me that the source an sink variables are empty.

Manually with this command I'm getting my device working fine:

pactl load-module module-loopback source=bluez_source.XX_XX_XX_XX_XX_XX
sink=alsa_output.platform-bcm2835_AUD0.0.analog-stereo

Any ideas why the debuggung looks like this:

~ $ tail -f /var/log/bluetooth_dev
BSOURCE=
sudo -u pi pactl load-module module-loopback source= sink= rate=44100 adjust_time=0
Executing bluetooth script...|add|
Executing bluetooth script...|add|
BSINK=
BSINK=
BSOURCE=
BSOURCE=
sudo -u pi pactl load-module module-loopback source= sink= rate=44100 adjust_time=0
sudo -u pi pactl load-module module-loopback source= sink= rate=44100 adjust_time=0

I hope it has nothing to do with my B+. I read something about a bad newer kernel, but an older Kernel I'm not able to install :-/

RobertR5 RobertR52 months ago

now it works automatically. I modified the bluetooth script (found here):


ACTION=$(expr "$ACTION" : "\([a-zA-Z]\+\).*")
if [ "$ACTION" = "add" ]; then
for f in /sys/devices/virtual/input/input*/name; do
mac=$(cat $f|sed 's/:/_/g')
sleep 1
if [ ! -z "$(su - pi -c 'pactl list short|grep '$mac)" ]; then
su - pi -c 'pactl load-module module-loopback source=bluez_source.'$mac' sink=alsa_output.platform-bcm2835_AUD0.0.analog-stereo rate=44100 adjust_time=0'
fi
done
fi

the scripts starts with the original string:

SUBSYSTEM=="input", GROUP="input", MODE="0660"
KERNEL=="input[0-9]*", RUN+="/usr/lib/udev/bluetooth"

DanTheNugget3 months ago
I've had the same problem as Cole, has anyone fixed this yet?
DomR3 months ago

I have an odd problem, I've managed to get it to work, it will connect and play a song for about 10 seconds and then there will be no sound, the song will continue to play on my phone and it is still connected via bluetooth but no sound will come out!

To start it working again, I either have to restart the Pi or just restart bluetooth (sudo service bluetooth force-reload) and it will do the same thing.

Any ideas?

I have this exact same issue, I just set it up. I've looked at the running processes to see if just maybe bluetooth or pulse or maybe it died? Nope, i see them running the entire time (mine plays between 15 and 20 seconds then dies)

Ah yeah, other people have found what i found below in the comments. It's because pulseaudio is going to idle after 20 seconds. So there is a bit of code posted below to prevent that.

nreyes13 months ago

I'm having the same issue as Philrlewis

"Every time I try to set my class as 0x20041C in /var/lib/bluetooth/ it saves, but on reboot the class has reverted back to 0x4e041c. Any ideas how to stop this?"

Great instructable!!

I've followed the instructions closely, used the old kernel, and even followed some of the comment suggestions.
However, I'm getting "Connection Unsuccessful - Make sure bluetooth is on and in range"
Looks like the bluetooth blue light comes on intermittently on the Pi.

Any thoughts would be greatly appreciated!

Never got this working but here's a working Rasbpi-Bluetooth tutorial instead:

http://www.reddit.com/r/raspberry_pi/comments/28ogmo/i_made_my_pi_an_incar_bluetooth_audio_receiver/

To follow up, I've tried these two bluetooth models off Amazon, both confirmed working with Raspberry Pi in the Amazon reviews. I don't think they're faulty here.

http://www.amazon.com/gp/product/B00H8O8CMO/ref=oh... (Low energy bluetooth)

http://www.amazon.com/gp/product/B00AKO7XOW/ref=oh... (Regular bluetooth)

I've also tried all the applicable comment recommendations (Diff script, diff kernel, etc.)

Running this didn't return anything.

tail -f /var/log/bluetooth_dev

RPCALIVE4 months ago

sudo apt-get upgrade should be sudo apt-get update

lukeg019 months ago

hmmm..... seems to work, got a device with a headset sign in the list.... now just ONE terrible problem.... i can't find the PIN code.... 0000 and 1234 did not help

Luke

lukeg01 lukeg019 months ago

fixed it using bluez agent, now... no audio not even for 20 sec, maybe worth noting, i'm using "Xbian" instead of raspbian, meaning everything with alas needs
needs the "sudo" command

Luke

DusanKo lukeg015 months ago

Hello,

I hope i did not make two posts:)

Can You please give step by step instuctions how You managed the PIN pairing with bluez?

thank You lukeg01

wapenv5 months ago

After the 20 seconds fix it worked for me! But I'm searching for a command that stops playing... Because I also want to play internet radio...Someone a idea?

tbailey965 months ago

Thanks for this, I tried a few other methods before this one and couldn't make them work, this works, but the volume of the output from the 3.5mm jack is very low, as a result I need my amp turned up really high. I tried to fix this by increasing the master volume in the Bluetooth script to 200%, and that didn't have any affect, so has anyone got any ideas on how to make the pi kick out more volume? :)

Thanks In Advance,

Tom.

sigilium5 months ago

Thanks for this, worked like a charm. Tomorrow morning my Raspi starts a new life in my car :)

I get quite nasty background noise from the analog output. Hope it's not so bad in car!

1-40 of 178Next »