Tutorial

Playing music with python on a Raspberry Pi

noras noras |

Tags: #Python #Raspberry pi

The idea

Few months ago I wanted to use my new Raspberry Pi 3 to play music. My basic idea was to create a simple controller mobile application.
The protocol it self goes throughout four steps assuming I will have all my music files on the pi:

  • The app asks for the the list.
  • The raspberry pi respond with the list
  • The app asks to play a song from the list
  • The pi plays the song then sends a success message

 

Setup

For this setup you need:

  • a Raspberry Pi with an OS that you can run Python on.
  • Python with pygame installd
  • Speakers connected to your raspberry pi or connect your raspberry pi using HDMI to a screen with speakers

Don’t forget to chose the default audio output if you go with the external speaker option.

 

Python code

While this article will only cover the music playing part. I will try write an article about the process of using sockets or web sockets in your applications and link it here when its done, to show how I made my controler.
To start, I needed a light weight music player that is able to play my music.
After a small research I was able to find that the pygame that comes with the raspbian stretch by default is very easy to implement.


import pygame
pygame.mixer.init()
pygame.mixer.music.load("Music/myMp3file.mp3")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
continue

 

What’s next

The next step for you is to explore the pygame mixer functions and try to use it in a socket server and make a client to request certain things.


About the author

noras

"Senior Software Engineer. MSc in Computer systems and Networks with big interest in security. Loves to play with Android code and does security research for fun and profit. Speaks 4 languages and codes in much more."

Related articles

Tags: #Python #Raspberry pi




Copyright © 2019 - nindoda.com