How to Build a Music Player using Django

spyrokp@gmail.com Avatar

Django is a high-level, open-source web framework for building

dynamic web applications in the Python programming language. It follows the model-view-controller (MVC) architectural pattern and emphasizes the principle

of don\’t repeat yourself (DRY), which promotes code reusability and reduces redundancy.

Django provides a rich set of features out of the box,

such as object-relational mapping (ORM) for database integration, a built-in admin interface for managing website content, a powerful templating engine for rendering HTML,

and robust URL routing for mapping URLs to views. These features make it easy to create complex,

database-driven web applications quickly and efficiently.

Django also includes a variety of third-party packages,

called \”apps,\” which provide additional functionality and can be easily integrated into projects. Some popular Django apps include Django REST framework for building APIs,

Django Channels for handling real-time web sockets, and Django Celery for asynchronous task processing.

Django has a large and active community of developers who contribute to its ongoing development and provide support through online forums, documentation, and tutorials. Its popularity is due in part to its ease of use, flexibility, and scalability, which make it an excellent choice for building web applications of all sizes and complexity levels.

How to build this

To build an online music player, you will need to use a combination of front-end and back-end web development technologies. Here are the general steps you can follow:

Define the requirements and functionalities of the music player:

Before you start building the player, it is essential to define the features and functionality that you want to include, such as search, playlist creation, music playback, etc.

Choose a front-end technology:

You will need to choose a front-end technology to create the user interface of your music player. Some popular options include React, Vue.js, and Angular.

Choose a back-end technology: You will need to choose a back-end technology to handle the server-side logic of your music player. Django and Node.js are popular options for building web applications.

Set up a database: You will need a database to store music files and metadata, such as artist name, album, and track name. MySQL or PostgreSQL are popular relational database options.

Build the user interface: Use your chosen front-end technology to create a user-friendly interface for the music player. Consider implementing features such as search, playlist creation, and playback controls.

Build the server-side logic:

Use your chosen back-end technology to implement the server-side logic for the music player. This can include functionality such as authentication, database integration, and API endpoints for retrieving music files and metadata.

Integrate with a music streaming service:

To play music, you can integrate your music player with a music streaming service API, such as Spotify or Apple Music.

Test and deploy: Test your music player thoroughly and deploy it to a web server or hosting platform, such as Heroku or AWS.

Building an online music player requires a good understanding of web development technologies and concepts. You may need to seek out tutorials, documentation, and support from the community to build a functional and user-friendly music player.

Creating our Django App

# create our project
django-admin startproject MusicPlayer

# change directory to project
cd MusicPlayer

# create our app
django-admin startapp App

The commands above should provide you with a directory structured as seen in the image below:

\"\"

Now go to the “MusicPlayer” directory and edit our settings.py file by adding our App to the list of installed apps as seen below.

INSTALLED_APPS = [
    \'django.contrib.admin\',
    \'django.contrib.auth\',
    \'django.contrib.contenttypes\',
    \'django.contrib.sessions\',
    \'django.contrib.messages\',
    \'django.contrib.staticfiles\',
    \'App\'
]

Now let’s create our static and templates folders in our APP directory. The template folder will house our HTML files, while the static folder will house our CSS, Javascript, and other static files.

To do this, run the command below on your command-line.

# changing directory to our app
cd App

# creating  the static and templates folders
mkdir templates
mkdir static

In the templates folder, create a new file “index.html” and add the HTML code below:

{% load static %}

<!DOCTYPE html>
<html lang=\"en\">
 <head>
  <meta charset=\"utf-8\"/>
  <title>
   My Music Player
  </title>
  <link href=\"https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css\" rel=\"stylesheet\"/>
  <link href=\"https://cdnjs.cloudflare.com/ajax/libs/mediaelement/4.2.7/mediaelementplayer.min.css\" rel=\"stylesheet\"/>
  <link href=\"{% static \'./style.css\' %}\" rel=\"stylesheet\"/>
 </head>
 <body>
  <!-- partial:index.partial.html -->
  <html>
   <head>
    <meta charset=\"utf-8\"/>
    <title>
     Flat music player
    </title>
   </head>
   <body>
    <div class=\"contain\">
     <div class=\"container\">
      <div class=\"music-player\">
        {% for item in page_obj %}
       <div class=\"cover\">
        <img alt=\"\" src=\"{{item.image.url}}\"/>
       </div>
       <div class=\"titre\">
        <h3>
         {{item.artist}}
        </h3>
        <h1>
         {{item.title}}
        </h1>
       </div>
       <center><a href=\"{% if page_obj.has_previous %}?page={{ page_obj.previous_page_number }}{% endif %}\"><i class=\"fa fa-step-backward fa-2x\"></i></a> &nbsp; &nbsp; &nbsp; <a href=\"{% if page_obj.has_next %}?page={{ page_obj.next_page_number }} {% endif %}\"><i class=\"fa fa-step-forward fa-2x\"></i></a></center>
       <div class=\"lecteur\">
        <audio class=\"fc-media\" style=\"width: 100%;\">
         <source src=\"{% if item.audio_file %}{{item.audio_file.url}} {% else %} {{item.audio_link}} {% endif %}\" type=\"audio/mp3\"/>
        </audio>

       </div>
       {% endfor %}
      </div>
     </div>
    </div>
   </body>
  </html>
  <!-- partial -->
  <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js\">
  </script>
  <script src=\"https://cdnjs.cloudflare.com/ajax/libs/mediaelement/4.2.7/mediaelement-and-player.min.js\">
  </script>
  <script src=\"{% static \'./script.js\' %}\">
  </script>
 </body>
</html>

In the script.js file, add the following code as seen below:

var audio = {    
    init: function() {        
    var $that = this;        
        $(function() {            
            $that.components.media();        
        });    
    },
    components: {        
        media: function(target) {            
            var media = $(\'audio.fc-media\', (target !== undefined) ? target : \'body\');            
            if (media.length) {                
                media.mediaelementplayer({                    
                    audioHeight: 40,
                    features : [\'playpause\', \'current\', \'duration\', \'progress\', \'volume\', \'tracks\', \'fullscreen\'],
                    alwaysShowControls      : true,
                    timeAndDurationSeparator: \'<span></span>\',
                    iPadUseNativeControls: true,
                    iPhoneUseNativeControls: true,
                    AndroidUseNativeControls: true                
                });            
            }        
        },
            
    },
};

audio.init();

Next, let’s first import the os module in our settings.py file. To import the os module add the code below to the top of the settings.py file.

import os

We should also define our static_rootmedia_root, and media_url in our settings.py file as seen below:
STATIC_URL = \'/static/\'
STATIC_ROOT = os.path.join(BASE_DIR, \'static\')
MEDIA_ROOT =os.path.join(BASE_DIR, \'media\')
MEDIA_URL = \'/media/\'

In the “MusicPlayer” directory, edit the urls.py file to:

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib.staticfiles.urls import static

urlpatterns = [
    path(\'admin/\', admin.site.urls),
    path(\'\', include(\"App.urls\")),

]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Goto back to our App directory and create a new file called urls.py. Here we would define the URLs the root Django project would be linked to. After creating the new urls.py file, add the following code to it:

from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include
from . import views

app_name = \"App\"

urlpatterns = [
    path(\"\", views.index, name=\"index\"),
]

In the “App” directory, edit the models.py file and add the following lines of code to it.

from django.db import models

# Create your models here.
class Song(models.Model):
    title= models.TextField()
    artist= models.TextField()
    image= models.ImageField()
    audio_file = models.FileField(blank=True,null=True)
    audio_link = models.CharField(max_length=200,blank=True,null=True)
    duration=models.CharField(max_length=20)
    paginate_by = 2

    def __str__(self):
        return self.title

Next, go to the views.py file in the same directory.

Edit the file and add the following lines of code:

# Create your views here.
from django.shortcuts import render, redirect

# imported our models
from django.core.paginator import Paginator
from . models import Song

def index(request):
    paginator= Paginator(Song.objects.all(),1)
    page_number = request.GET.get(\'page\')
    page_obj = paginator.get_page(page_number)
    context={\"page_obj\":page_obj}
    return render(request,\"index.html\",context)

Finally, we can migrate our model to the database by using the below command on the command-line in the root directory where we can find our manage.py file.

# migrating the app and database changes
python manage.py makemigrations

# final migrations
python manage.py migrate

The result of running the above migrations should look like the image below:

\"\"

You will also notice our SQLite database file was created in the root folder for us easily. The root directory file should look like the image seen below:

\"\"

The admin.py file can be found in the App folder. Edit and add the following code.

from django.contrib import admin
from . models import Song

# Register your models here.
admin.site.register(Song)

To create a superuser enter the below command in your command-line:

python manage.py createsuperuser

Let’s now run our app with the command below.

python manage.py runserver

\"\"

To login to the admin page go to this link http://127.0.0.1:8000/admin and enter your login details as seen in the image below:

\"\"

If your login was successful you should now see the page below:

\"\"

Click on the add button where you have the Songs panel and enter the song details as seen below. Add two or three more songs by clicking on the “add and save another” button at the bottom right of the page as seen in the image below:

\"\"

You can view it on your localhost at this link http://127.0.0.1:8000/ and you should have a music player like the one in the image below:

\"\"