One place for hosting & domains

      Music

      Installieren des Ampache Music Streaming-Servers unter Ubuntu 18.04


      Der Autor hat den Open Internet/Free Speech Fund dazu ausgewählt, eine Spende im Rahmen des Programms Write for DOnations zu erhalten.

      Einführung

      Ampache ist ein Open-Source Musik-Streaming-Server, der es Ihnen ermöglicht, Ihre digitale Musiksammlung auf Ihrem eigenen Server zu hosten und zu verwalten. Ampache kann Ihre Musik an Ihren Computer, Smartphone, Tablet oder Smart TV streamen. Das bedeutet, dass Sie keine Mehrfachkopien Ihrer Musik auf dem Gerät, das Sie zum Anhören verwenden möchten, verwalten müssen. Mit Ampache können Sie Ihre Sammlung auf Ihrem Server über die Webschnittstelle von Ampache verwalten und an jedem beliebigen Ort anhören.

      In diesem Tutorial werden Sie den Apache-Webserver und PHP installieren und konfigurieren, die Ihre Ampache-Instanz bedienen werden. Anschließend erstellen Sie eine MySQL-Datenbank, die Ampache zur Speicherung aller Betriebsinformationen verwendet. Abschließend werden Sie Ihre Musiksammlung hochladen, damit Sie mit dem Streaming Ihrer Musik beginnen können.

      Voraussetzungen

      Bevor Sie diese Anleitung beginnen, benötigen Sie Folgendes:

      • Einen Ubuntu-18.04-Server, der gemäß dem Tutorial Ersteinrichtung eines Servers mit Ubuntu 18.04 eingerichtet wurde, einschließlich eines non-root sudo user.
      • Auf Ihrem Server installiertes Apache, MySQL und PHP, wie in Installieren des Linux-, Apache-, MySQL-, PHP (LAMP)-Stacks unter Ubuntu 18.04 gezeigt.
      • Einen Domänennamen, der so konfiguriert ist, dass er auf Ihren Server verweist. Sie können lernen, wie Sie Domänen auf DigitalOcean Droplets verweisen, indem Sie dem Tutorial Einrichten eines Hostnamens mit DigitalOcean folgen.

      Schritt 1 — Installieren von Ampache

      In diesem Schritt laden Sie das Ampache-ZIP-Archiv auf Ihren Server herunter, entpacken es in das Home-Verzeichnis der Installation und nehmen einige notwendige Änderungen am Dateisystem vor.

      Melden Sie sich zunächst als non-root user bei Ihrem Server an. Erstellen Sie dann das Home-Verzeichnis von Ampache mit dem folgenden Befehl:

      • sudo mkdir /var/www/ampache

      Installieren Sie als Nächstes das Dienstprogramm zip, das Sie zum Entpacken des Ampache-Archivs benötigen:

      Laden Sie anschließend das ZIP-Archiv der neuesten Version herunter. Den Link zu der neuesten Version finden Sie auf der GitHub-Seite von Ampache. In diesen Beispielen wird Version 4.1.1 verwendet:

      • wget https://github.com/ampache/ampache/releases/download/4.1.1/ampache-4.1.1_all.zip

      Entpacken Sie dann das ZIP-Archiv in das Verzeichnis /var/www/ampache/ mit der Option -d:

      • sudo unzip ampache-4.1.1_all.zip -d /var/www/ampache/

      Legen Sie danach die Benutzer- und Gruppenidentität der Dateien von Ampache fest, sodass Apache die Ampache-Instanzdateien lesen, schreiben und ausführen kann:

      • sudo chown --recursive www-data:www-data /var/www/ampache/

      Die Option --recursive veranlasst chown, die Eigentümerschaft und die Gruppenidentität aller Dateien und des Unterverzeichnisses unter /var/www/ampache/ auf die Benutzer und Gruppen www-data von Apache zu ändern.

      Benennen Sie anschließend die .htaccess-Dateien, die im ZIP-Archiv enthalten sind, um. .htaccess-Dateien enthalten Sicherheits- und andere Betriebsinformationen für Apache, aber sie funktionieren nur mit der Dateierweiterung .htaccess. Benennen Sie die bereitgestellte .htaccess.dist-Datei mit den folgenden Befehlen in .htaccess um:

      • sudo mv /var/www/ampache/rest/.htaccess.dist /var/www/ampache/rest/.htaccess
      • sudo mv /var/www/ampache/play/.htaccess.dist /var/www/ampache/play/.htaccess
      • sudo mv /var/www/ampache/channel/.htaccess.dist /var/www/ampache/channel/.htaccess

      Jetzt erstellen Sie das Verzeichnis, das Ihre Musikdateien enthalten wird. Aus Sicherheitsgründen wird dieses Verzeichnis am besten außerhalb des Installationsverzeichnisses von Ampache angelegt. Auf diese Weise kann es nicht von böswilligen Web-Abfragen gelesen oder geändert werden, da es sich außerhalb des DocumentRoot von Ampache befindet.

      Erstellen Sie das Verzeichnis /data/Music mit dem folgenden Befehl:

      • sudo mkdir -p /data/Music

      Ändern Sie dann seinen Eigentümer und die Gruppenidentität, damit Apache es lesen und darin schreiben kann:

      • sudo chown www-data:www-data /data/Music

      Um die Einrichtung abzuschließen, installieren Sie FFmpeg, ein Dienstprogramm, das Audio und Video von einem Format in ein anderes konvertiert. Sie könnten es zum Beispiel verwenden, um eine MP3-Musikdatei in eine OPUS-Musikdatei zu konvertieren. Ampache verwendet FFmpeg, um Audio ohne Vorbereitung aus dem Format, in dem es hochgeladen wurde, in ein Format zu konvertieren, das das Wiedergabegerät abspielen kann. Dies ist ein Vorgang, der als Transkodierung bekannt ist.

      Dies ist nützlich, da nicht alle Geräte alle Musikformate wiedergeben können. Ampache kann erkennen, welche Formate auf dem Wiedergabegerät unterstützt werden, und Ihre Musik automatisch in dem unterstützten Format bereitstellen.

      Installieren Sie FFmpeg mit dem folgenden Befehl:

      Sie haben nun Ihre Ampache-Instanz entpackt und für das Web-Installationsprogramm vorbereitet sowie das Dienstprogramm FFmpeg installiert. Als Nächstes konfigurieren Sie Apache und PHP, um Ihre Ampache-Instanz zu bedienen.

      Schritt 2 – Konfigurieren von Apache und PHP

      In diesem Abschnitt konfigurieren Sie Apache, indem Sie eine neue VirtualHost-Datei erstellen, die die Konfiguration bereitstellt, die Apache zur Bedienung Ihrer Ampache-Serverdomäne benötigt. Sie werden auch einige zusätzliche PHP-Module installieren, die die Fähigkeiten von PHP erweitern, um die Anforderungen von Ampache abzudecken.

      Installieren Sie zunächst einige zusätzliche PHP-Module, die nicht in der Standardinstallation von PHP enthalten waren:

      • sudo apt install php-mysql php-curl php-json php-gd php7.2-xml

      Diese Module bieten die folgenden zusätzlichen Funktionen:

      • php-mysql – Ermöglicht PHP die Kommunikation mit einer MySQL-Datenbank.
      • php-curl – Ermöglicht PHP die Verwendung des Dienstprogramms curl zum Herunterladen von Dateien, wie beispielsweise Album-Cover-Kunst, von entfernten Servern.
      • php-json – Ermöglicht PHP, JSON-formatierte Textdateien zu lesen und zu bearbeiten.
      • php-gd – Ermöglicht PHP die Bearbeitung und Erstellung von Bilddateien.
      • php7.2-xml – Ermöglicht PHP das Lesen und Bearbeiten von XML-formatierten Textdateien.

      Aktivieren Sie anschließend einige Apache-Module mit dem Dienstprogramm a2enmod:

      • sudo a2enmod rewrite expires

      Diese Apache-Module ermöglichen Apache Folgendes:

      • rewrite – Modifizieren oder Neuschreiben von URLs nach den von Ampache gelieferten Regeln.
      • expires – Einstellen der Cache-Verfallszeiten für Objekte wie Bilder, damit diese von den Browsern effizienter gespeichert werden.

      Nun werden Sie die VirtualHost-Datei erstellen, die Apache mitteilt, wie und wo die Ampache-Instanz geladen werden soll.

      Anmerkung: Wenn Sie eine Testdatei VirutalHost erstellt haben, die Ihren Ampache-Domänennamen verwendet, als Sie dem Leitfaden “Installieren eines Linux-, Apache-, MySQL-, PHP (LAMP)-Stack unter Ubuntu 18.04″gefolgt sind, müssen Sie dises deaktivieren. Verwenden Sie zum Deaktiveren das Dienstprogramm a2dissite:

      • sudo a2dissite test_virtalhost_file

      Erstellen und öffnen Sie nun die VirtualHost-Datei mit Ihrem Texteditor unter /etc/apache2/sites-available/ampache.conf:

      • sudo nano /etc/apache2/sites-available/ampache.conf

      Fügen Sie die folgende VirtualHost-Vorlage in Ihre Datei ein:

      /etc/apache2/sites-available/ampache.conf

      <VirtualHost *:80>
      
          ServerName your_domain
          DocumentRoot /var/www/ampache
      
          <Directory /var/www/ampache/>
              AllowOverride All
              Require all granted
          </Directory>
      
          RewriteEngine on
          CustomLog /var/log/apache2/ampache.access.log common
          ErrorLog  /var/log/apache2/ampache.error.log
      
      </VirtualHost>
      

      Sie müssen your_domain in den Domänennamen ändern, den Sie auf Ihren Server umgeleitet haben. Wenn Sie die Bearbeitung dieser Datei abgeschlossen haben, speichern Sie sie und verlassen Sie den Editor.

      Die Anweisungen in dieser VirtualHost-Datei lauten:

      • ServerName – Der Domänenname, den Apache zur Bedienung Ihrer Ampache-Instanz verwendet.
      • DocumentRoot – Der Speicherort des Dateisystems auf Ihrem Server, an dem sich die Ampache-Instanz befindet. Dies ist der gleiche Ort, in den Sie in Schritt 1 das ZIP-Archiv entpackt haben.
      • Directory – Dieser Abschnitt übergibt eine Konfiguration an Apache, die für die im Pfad enthaltenen Dateien und Verzeichnisse gilt.
      • RewriteEngine – Aktiviert das Apache-Modul zum Neuschreiben von Dateien.
      • CustomLog – Erstellt eine Protokolldatei, die Apache zur Aufzeichnung aller Zugriffsprotokolle für Ihren Ampache-Server verwendet.
      • ErrorLog – Erstellt eine Protokolldatei, die Apache zur Aufzeichnung aller von Ihrem Ampache-Server erzeugten Fehlerprotokolle verwendet.

      Prüfen Sie anschließend mit dem Dienstprogramm apachectl, ob die von Ihnen erstellte VirtualHost-Datei fehlerfrei ist:

      • sudo apachectl configtest

      Wenn Ihre Konfiguration keine Fehler enthält, sehen Sie nach dem Befehl die folgende Ausgabe:

      Output

      Syntax OK

      Wenn Ihre Konfiguration Fehler enthält, werden in der Ausgabe der Dateiname und die Zeilennummer, in der der Fehler aufgetreten ist, ausgegeben.

      Anmerkung: Wenn Sie den Fehler sehen:

      AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
      

      Dann müssen Sie die Hauptkonfigurationsdatei von Apache unter /etc/apache2/apache2.conf bearbeiten und die folgende Zeile hinzufügen:

      ServerName your_domain
      

      Aktivieren Sie anschließend die neue VirtualHost-Konfiguration mit dem Dienstprogramm a2ensite:

      Die endgültige Konfiguration ist optional, wird jedoch empfohlen. Die Standardeinstellung für Datei-Uploads in PHP ist, dass Dateien, die größer als 2 MB sind, nicht hochgeladen werden können. Musikdateien neigen dazu, größer zu sein. Wenn Sie diesen Wert erhöhen, können Sie die Ampache-Schnittstelle verwenden, um größere Dateien in Ihrer Musiksammlung hochzuladen.

      Öffnen Sie /etc/php/7.2/apache2/php.ini mit dem folgenden Befehl:

      • sudo nano /etc/php/7.2/apache2/php.ini

      Und ändern Sie die folgenden Zeilen:

      /etc/php/7.2/apache2/php.ini

      . . .
      upload_max_filesize = 2M
      . . .
      post_max_size = 8M
      . . .
      

      Zu:

      /etc/php/7.2/apache2/php.ini

      . . .
      upload_max_filesize = 100M
      . . .
      post_max_size = 110M
      . . .
      

      Sie können nun Musikdateien bis zu 100 MB hochladen. Verwenden Sie einen größeren Wert, wenn Sie beabsichtigen, Dateien mit darüber hinausgehender Größe hochzuladen. Speichern und schließen Sie die Datei.

      Laden Sie abschließend Ihre aktualisierte Apache-Konfiguration neu:

      • sudo systemctl reload apache2.service

      Sie haben Apache jetzt so konfiguriert, dass Ampache über HTTP bedient wird. Als Nächstes erhalten Sie ein TLS-Zertifikat und konfigurieren Apache zur Verwendung desselben, sodass Sie über HTTPS sicher auf Ampache zugreifen können.

      Schritt 3 – Aktivieren von HTTPS

      In diesem Schritt erhalten Sie mit dem Dienstprogramm Certbot ein kostenloses Let’s Encrypt TLS-Zertifikat, das HTTPS ermöglicht. Certbot erstellt das Zertifikat, generiert automatisch die erforderliche Apache-Konfiguration und verwaltet die automatische Erneuerung des Zertifikats.

      Dies ist wichtig, denn Sie senden bei jeder Anmeldung bei Ampache Ihren Benutzernamen und Ihr Passwort über das Internet. Wenn Sie kein HTTPS verwenden, wird Ihr Passwort im Klartext verschickt, der auf seinem Weg durch das Internet gelesen werden kann.

      Die LTS-Veröffentlichungen von Ubuntu neigen dazu, nicht über die aktuellsten Pakete zu verfügen, und dies trifft auch auf das Certbot-Programm zu. Die Certbot-Entwickler unterhalten ein dediziertes Ubuntu-Repository, das als PPA bekannt ist, sodass Ubuntu-Benutzer eine aktuelle Kopie des Certbot verwenden können.

      Installieren Sie das Certbot-Repository mit dem folgenden Befehl:

      • sudo add-apt-repository ppa:certbot/certbot

      Installieren Sie nun das Dienstprogramm certbot:

      • sudo apt install python-certbot-apache

      Verwenden Sie anschließend certbot, um das TLS-Zertifikat zu erhalten:

      • sudo certbot --apache -d your_domain

      Die Option --apache verwendet das Apache-Plugin, das es Certbot ermöglicht, Apache automatisch zu lesen und zu konfigurieren. -d your_domain gibt den Domänennamen an, für den Cerbot das Zertifikat erstellen soll.

      Wenn Sie den Befehl certbot ausführen, werden Ihnen eine Reihe von Fragen gestellt. Sie werden zur Eingabe einer E-Mail-Adresse und der Zustimmung zu den Nutzungsbedingungen aufgefordert.

      Wenn certbot erfolgreich bestätigt, dass Sie Ihre Domäne kontrollieren, werden Sie aufgefordert, Ihre HTTPS-Einstellungen zu konfigurieren:

      Output

      Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access. ------------------------------------------------------------------------------- 1: No redirect - Make no further changes to the webserver configuration. 2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for new sites, or if you're confident your site works on HTTPS. You can undo this change by editing your web server's configuration. ------------------------------------------------------------------------------- Select the appropriate number [1-2] then [enter] (press 'c' to cancel):
      • No redirect: Apache bedient Ampache über HTTP und HTTPS.
      • Redirect: Apache leitet alle HTTP-Verbindungen automatisch zu HTTPS um. Das bedeutet, dass Ihr Ampache-Server nur über HTTPS verfügbar ist. Diese Option ist die sicherere und hat keinen Einfluss darauf, wie sich Ihre Ampache-Instanz verhält. Dies ist die empfohlene Wahl.

      Testen Sie abschließend, ob die automatische Erneuerung des Zertifikats erfolgreich abläuft, indem Sie den folgenden Befehl ausführen:

      • sudo certbot renew --dry-run

      Die Option --dry-run bedeutet, dass certbot einen Erneuerungsversuch testet, ohne dauerhafte Änderungen an Ihrem Server vorzunehmen. Wenn der Test erfolgreich war, enthält die Ausgabe die folgende Zeile:

      Output

      Congratulations, all renewals succeeded. The following certs have been renewed: /etc/letsencrypt/live/your_domain/fullchain.pem (success)

      Apache und PHP können nun Ihre Ampache-Instanz bedienen. Im nächsten Schritt erstellen und konfigurieren Sie die Datenbank von Ampache.

      Schritt 4 — Erstellen einer MySQL-Datenbank

      Ampache verwendet eine MySQL-Datenbank, um Informationen wie Wiedergabelisten, Benutzereinstellungen usw. zu speichern. In diesem Schritt erstellen Sie eine Datenbank und einen MySQL-Benutzer, mit denen Ampache auf diese Datenbank zugreift.

      Sie müssen drei Informationen auswählen, um die folgenden Anweisungen zur Erstellung der Datenbank von Ampache auszuführen:

      1. ampache_database: Der Name der Ampache-Datenbank.
      2. database_user: Der MySQL-Benutzer, den Ampache für den Zugriff auf die Datenbank verwenden wird. Dieser ist kein Systembenutzer und kann nur auf die Datenbank zugreifen.
      3. database_password: Das Passwort des Datenbankbenutzers. Achten Sie darauf, ein sicheres Passwort zu wählen.

      Notieren Sie sich diese Angaben, da Sie sie später benötigen werden.

      Öffnen Sie zunächst die interaktive MySQL-Shell mit dem Befehl mysql:

      • mysql --user=root --password

      --user=root öffnet die MySQL-Shell als root user von MySQL und --password fordert zur Eingabe des Passworts des root users auf.

      Der folgende Befehl erstellt eine leere Datenbank:

      • CREATE DATABASE ampache_database;

      Erstellen Sie anschließend den MySQL-Benutzer:

      • CREATE USER 'database_user'@'localhost' IDENTIFIED BY 'database_password';

      Geben Sie dem neuen Benutzer nun vollen Zugriff auf die Datenbank:

      • GRANT ALL PRIVILEGES ON ampache_database.* TO 'database_user'@'localhost';

      Überprüfen Sie abschließend, ob die neue Datenbank vorhanden ist, indem Sie den folgenden Befehl ausführen:

      Sie sehen die folgende Ausgabe:

      +--------------------+
      | Database           |
      +--------------------+
      | information_schema |
      | ampache_database  |
      | mysql              |
      | performance_schema |
      | sys                |
      +--------------------+
      5 rows in set (0.00 sec)
      

      Verlassen Sie die MySQL-Shell durch Eingabe von exit;.

      Testen Sie abschließend die Datenbank, den Benutzernamen und das Passwort, indem Sie versuchen, sich mit dem database_user an der MySQL-Shell anzumelden.

      Geben Sie den folgenden Befehl ein, um sich als neuer Benutzer an der MySQL-Shell anzumelden:

      • mysql --user=database_user --password ampache_database

      Sie haben nun die Datenbank erstellt, die Ampache verwenden wird. Sie haben Ihre Serverkonfiguration abgeschlossen und sind bereit, die Installation mit dem Webinstaller abzuschließen.

      Schritt 5 — Verwenden des Webinstallers

      In diesem Schritt verwenden Sie den Webinstaller von Ampache, um die Installation abzuschließen, indem Sie Ampache die Informationen geben, die es zum Ausführen benötigt, wie z. B. einen Weboberflächen-Adminbenutzer, die Datenbankdetails und andere Einstellungen.

      Beginnen Sie die Web-Installation, indem Sie https://your_domain in Ihren Browser eingeben.

      Wählen Sie die Installationssprache

      Wählen Sie die Sprache der Benutzeroberfläche von Ampache und klicken Sie auf die Schaltfläche Start Configuration, um fortzufahren.

      Anforderungen

      Auf dieser Seite überprüft Ampache, ob der Server die Anforderungen erfüllt. Jede Zeile auf dieser Seite stellt einen Test dar, den das Installationsprogramm durchführt, um sicherzustellen, dass z. B. alle erforderlichen PHP-Module vorhanden sind und funktionieren. Sie werden sehen, dass jeder Test mit einem grünen Häkchen versehen ist, um anzuzeigen, dass Ihr Server für Ampache bereit ist.

      Klicken Sie auf die Schaltfläche Continue, um zur nächsten Seite zu gelangen.

      Einfügen der Ampache-Datenbank (Insert Ampache Database)

      Diese Seite erstellt die Datenbank von Ampache, falls sie nicht existiert, und formatiert sie. Füllen Sie die Felder wie folgt aus:

      • Desired Database Name: ampache_database
      • MySQL Hostname: localhost
      • MySQL Port (optional):<EMPTY>
      • MySQL Administrative Username: database_user
      • MySQL Administrative Password: database_password
      • Create Database:<UNCHECKED>
      • Create Tables (ampache.sql):<CHECKED>
      • Create Database User:<UNCHECKED>

      Bild des ausgefüllten Formulars

      Klicken Sie auf die Schaltfläche Insert Database, um fortzufahren.

      Erstellen der Konfigurationsdatei (Generate Configuration File)

      Diese Seite erstellt die Konfigurationsdatei, die Ampache zur Ausführung verwenden wird. Füllen Sie die Felder wie folgt aus:

      • Web Path:<EMPTY>

      • Database Name: ampache_database

      • MySQL Hostname: localhost

      • MySQL Port (optional):<EMPTY>

      • MySQL Username: database_user

      • MySQL Password: database_password

      Bild des ausgefüllten Formulars

      • Installation Type Belassen Sie dies bei der Standardeinstellung.

      • Allow Transcoding Wählen Sie aus der Dropdown-Liste ffmpeg aus.

      • Players Belassen sie diese bei den Standardeinstellungen.

      Klicken Sie auf die Schaltfläche Create Config, um fortzufahren.

      Erstellen des Admin-Kontos (Create Admin Account)

      Diese Seite erstellt den ersten Benutzer der Weboberfläche. Dieser Benutzer wird mit vollen administrativen Berechtigungen erstellt und ist derjenige, mit dem Sie sich zum ersten Mal anmelden und Ampache konfigurieren werden.

      Wählen Sie einen Benutzernamen und ein sicheres Passwort und geben Sie es in die Felder Password und Confirm Password ein.

      Klicken Sie auf die Schaltfläche Create Account, um fortzufahren.

      Ampache Update

      Auf dieser Seite werden alle administrativen Änderungen an der Datenbank von Ampache durchgeführt, die vorgenommen werden müssen. Diese Änderungen werden bei Versions-Upgrades vorgenommen, aber da es sich um eine Neuinstallation handelt, wird das Installationsprogramm keine Änderungen vornehmen.

      Klicken Sie auf die Schaltfläche Update Now!, um fortzufahren.

      Ampache Update

      Diese Seite zeigt und erklärt alle Aktualisierungen, die das Installationsprogramm im vorherigen Schritt vorgenommen hat. Sie sollten keine Aktualisierungen aufgelistet sehen.

      Klicken Sie auf den Link [Return to main page] (Zurück zur Hauptseite), um mit der Anmeldeseite fortzufahren. Geben Sie Ihren Benutzernamen und Ihr Passwort ein, das Sie für die Anmeldung bei Ihrem Ampache-Server festgelegt haben.

      Ampache ist noch nicht ganz fertig eingerichtet und nicht ganz einsatzbereit. Sie schließen nun die Einrichtung ab, indem Sie Ihre Musik hinzufügen, damit Sie Ihren neuen Ampache-Server nutzen können.

      Schritt 6 — Hinzufügen Ihrer Musik zu Ampache

      Ein Musikserver nützt nichts, wenn keine Musik zur Wiedergabe vorhanden ist. In diesem Schritt werden Sie einen Musikkatalog konfigurieren und Musik hochladen. „Catalog“ ist der Name, den Ampache einer Musiksammlung gibt. Ampache kann Musik aus vielen Quellen sowohl auf dem Server als auch außerhalb des Servers lesen, aber in diesem Tutorial werden Sie Ihre Musik auf den Server hochladen und in einem lokalen Katalog, wie Ampache ihn bezeichnet, speichern.

      Klicken Sie zunächst auf den Link add a Catalog in der folgenden Zeile auf der ersten Seite, die Sie sehen, wenn Sie sich bei Ampache anmelden.

      No Catalog configured yet. To start streaming your media, you now need to add a Catalog.

      Dadurch gelangen Sie zu der Seite Add Catalog. Füllen Sie die Felder wie folgt aus:

      • Catalog Name: Geben Sie dem Katalog einen kurzen, einprägsamen Namen.
      • Catalog Type: local
      • Filename Pattern:<EMPTY>
      • Folder Pattern: Belassen Sie dies mit den Standardeinstellungen.
      • Gather Art:<CHECKED>
      • Build Playlists from Playlist Files. (m3u, m3u8, asx, pls, xspf):<UNCHECKED>
      • Path: /data/Music

      Bild des ausgefüllten Formulars Katalog hinzufügen

      Klicken Sie auf die Schaltfläche Add Catalog, um diese Seite abzuschließen.

      Auf der folgenden Seite klicken Sie auf die Schaltfläche Continue. Sie gelangen auf die Seite Show Catalogs, auf der die Details zu dem von Ihnen erstellten Katalog angezeigt werden. Sie können die Katalogeinstellungen jederzeit später ändern.

      Aktivieren Sie nun die Web-Upload-Funktion von Ampache, indem Sie auf das dritte Navigationssymbol klicken, um die erweiterten Einstellungen zu öffnen:

      Bild des dritten Einstellungssymbols

      Scrollen Sie nach unten zu dem Abschnitt Server Config und klicken Sie auf den Link System, um die Seite mit den Systemeinstellungen zu öffnen.

      Suchen Sie die Zeile Allow user uploads und wählen Sie Enable aus dem Dropdown-Menü in der Spalte Value.

      Sie können auch wählen, welche Benutzerebene Musikdateien hochladen darf. Die Standardebene ist Catalog Manager, die es dem Catalog Manager und allen Benutzern mit höheren Berechtigungen ermöglicht, Musik hochzuladen. In diesem Fall ist das der Administrator.

      Sie müssen auch den Katalog festlegen, zu dem die Musik hinzugefügt werden soll. Legen Sie dies mit der Zeile Destination catalog fest. Wählen Sie in der Dropdown-Liste Value den von Ihnen erstellten Katalog aus.

      Bild mit Darstellung der Zeilen „Upload erlauben“ und „Zielkatalog“

      Klicken Sie am unteren Ende der Seite auf die Schaltfläche Update Preferences, um die Konfiguration abzuschließen. Sie können nun Musik hochladen.

      Klicken Sie zunächst auf das erste Einstellungensymbol:

      Symbol zeigt das erste Einstellungensymbol

      Klicken Sie dann im Abschnitt Music auf den Link Upload.

      Bild zeigt Link zum Upload

      Klicken Sie auf der Seite Upload die Schaltfläche Browse und suchen Sie Ihre Musikdateien auf Ihrem Computer und laden Sie sie hoch.

      Wenn Sie die Angaben Artist und Album leer lassen, liest Ampache die ID3-Tags der Musikdateien, um den Künstler und das Album automatisch zu ermitteln. Nachdem Sie einige Musikdateien hochgeladen haben, können Sie diese nun finden, indem Sie auf die Links Songs, Albums oder Artists im Abschnitt Music in der Navigationsleiste auf der linken Seite klicken.

      Ihr Ampache-Musikserver ist nun bereit, mit dem Streaming Ihrer Musik zu beginnen.

      Zusammenfassung

      In diesem Artikel haben Sie einen Ampache-Musik-Streaming-Server installiert und konfiguriert und einen Teil Ihrer Musik hochgeladen. Jetzt können Sie Ihre Musik überall auf jedem Ihrer Geräte wiedergeben. Die Dokumentation von Ampache hilft Ihnen bei der Verwendung und Erweiterung Ihres Streaming-Servers. Diese Android-Apps und diese iOS-App werden Ihre Musik auf Ihr Handy streamen. Ampache organisiert Ihre Musik auf dem Server anhand der ID3-Tags in den Musikdateien. Das Programm MusicMrainz hilft Ihnen bei der Verwaltung der ID3-Tags Ihrer Musikdateien.



      Source link

      Установка Ampache Music Streaming Server на Ubuntu 18.04


      Автор выбрал фонд Open Internet/Free Speech для получения пожертвований в рамках программы Write for DOnations.

      Введение

      Ampache — это сервер для потоковой трансляции музыки с открытым исходным кодом, который позволяет публиковать и управлять вашей цифровой музыкальной коллекцией на своем собственном сервере. Ampache может транслировать поток музыки на ваш компьютер, смартфон, планшет или телевизор с поддержкой технологии Smart TV. Вам больше не придется хранить вашу коллекцию музыки отдельно на каждом устройстве для прослушивания. Ampache позволит вам управлять вашей музыкой на сервере при помощи веб-интерфейса Ampache и прослушивать ее в любом месте, где бы вы не находились.

      В этом руководстве вы установите и настроите веб-сервер Apache и PHP, который будет обслуживать ваш экземпляр Ampache. Затем вы создадите базу данных MySQL, которая будет использоваться Ampache для хранения всей рабочей информации. В заключении вы загрузите свою коллекцию музыки для дальнейшей потоковой трансляции.

      Предварительные требования

      Для прохождения этого обучающего руководства вам потребуется следующее:

      • Один сервер Ubuntu 18.04, настроенный в соответствии с инструкциями по начальной настройке сервера с Ubuntu 18.04, а также non-root, sudo user.
      • Apache, MySQL, и PHP, установленные на вашем сервере согласно инструкциям из Установка стека Linux, Apache, MySQL, PHP (LAMP) на Ubuntu 18.04.
      • Доменное имя, настроенное так, чтобы указывать на ваш сервер. Вы можете узнать, как указывать домены на DigitalOcean Droplet, из руководства Настройка имени хоста с помощью DigitalOcean.

      Шаг 1 — Установка Ampache

      На этом шаге вы загрузите ZIP-архив Ampache на ваш сервер, распакуете его в домашнюю директорию для установки и внесете необходимые системные изменения.

      Войдите на сервер как non-root user. Создайте домашнюю директорию Ampache с помощью следующей команды:

      • sudo mkdir /var/www/ampache

      Установите утилиту zip для распаковки архива Ampache:

      Загрузите ZIP-архив с последней версией. Ссылка на последнюю версию находится на странице Ampache GitHub. В этом руководстве используется версия 4.1.1​:

      • wget https://github.com/ampache/ampache/releases/download/4.1.1/ampache-4.1.1_all.zip

      Распакуйте ZIP-архив в директорию /var/www/ampache/, используя опцию -d:

      • sudo unzip ampache-4.1.1_all.zip -d /var/www/ampache/

      Определите пользователя и групповую принадлежность файлов Ampache, чтобы Apache смог считывать, записывать и выполнять файлы экземпляра Ampache:

      • sudo chown --recursive www-data:www-data /var/www/ampache/

      Опция --recursive позволяет команде chown менять владельца и групповую принадлежность всех файлов, а также поддиректорию в /var/www/ampache на пользователя и группу www-data Apache.

      Переименуйте файлы .htaccess в ZIP-архиве. Файлы .htaccess содержат информацию по безопасности и рабочие данные Apache. Эти файлы могут работать только с расширением .htaccess. Переименуйте полученные файлы .htaccess.dist в .htaccess​​, выполнив следующие команды:

      • sudo mv /var/www/ampache/rest/.htaccess.dist /var/www/ampache/rest/.htaccess
      • sudo mv /var/www/ampache/play/.htaccess.dist /var/www/ampache/play/.htaccess
      • sudo mv /var/www/ampache/channel/.htaccess.dist /var/www/ampache/channel/.htaccess

      Далее вы создадите директорию для ваших музыкальных файлов. В целях обеспечения безопасности эта директория не должна находиться в директории с установочными файлами Ampache. Это защитит ее от считывания и злоумышленники не смогут внести изменения в нее, так как она будет находиться за пределами DocumentRoot​​​ Ampache.

      Создайте директорию /data/Music с помощью следующей команды:

      • sudo mkdir -p /data/Music

      Измените владельца и групповую принадлежность, чтобы Apache мог выполнять считывание и запись файлов:

      • sudo chown www-data:www-data /data/Music

      Для завершения настройки установите утилиту FFmpeg для конвертации аудио и видео из одного формата в другой. Например, вы сможете использовать ее для конвертации музыкального файла из MP3 формата в формат OPUS. Ampache использует FFmpeg для быстрой конвертации аудиофайла из формата загрузки в формат для проигрывания на устройстве. Этот процесс называется транскодингом.

      Он удобен, так как многие устройства не поддерживают воспроизведение всех форматов музыкальных файлов. Ampache может определять форматы, поддерживаемые устройством, и автоматически конвертировать загружаемые файлы в нужный формат.

      Установите FFmpeg с помощью следующей команды:

      Распаковка завершена, вы подготовили ваш экземпляр Ampache для веб-установщика и установили утилиту FFmpeg. Далее вы настроите Apache и PHP для обслуживания вашего экземпляра Ampache.

      Шаг 2 — Настройка Apache и PHP

      В этом разделе вы настроите Apache, создадите новый файл VirtualHost, который будет определять конфигурацию Apache для обслуживания вашего домена сервера Ampache. Вы также установите дополнительные модули PHP, расширяющие возможности PHP для удовлетворения требований Ampache

      Установите несколько дополнительных модулей PHP, которые не были включены в пакет установки PHP по умолчанию:

      • sudo apt install php-mysql php-curl php-json php-gd php7.2-xml

      Эти модули обеспечат следующие дополнительные возможности:

      • php-mysql​​​ — обеспечивает связь между PHP и базой данных MySQL.
      • php-curl​​​ — позволяет PHP использовать утилиту curl для загрузки файлов, например, обложек альбомов с внешних серверов.
      • php-json — позволяет PHP считывать и работать с текстовыми файлами в формате JSON.
      • php-gd​​​ — позволяет PHP создавать и работать с файлами изображений.
      • php7.2-xml​​​ – позволяет PHP создавать и работать с файлами в формате XML.

      Включите пару модулей Apache с помощью утилиты a2enmod:

      • sudo a2enmod rewrite expires

      Эти модули позволяют Apache выполнять следующее:

      • rewrite — изменяет или перезаписывает URL-адреса согласно правилам Ampache.
      • expires — определяет период хранения объектов, например, изображений, для повышенной эффективности хранения данных в браузере.

      Сейчас вы создадите файл VirtualHost, указывающий Apache на то, как и откуда загрузить экземпляр Ampache.

      Примечание. Если вы создали тестовый файл VirtualHost, в котором используется ваше доменное имя Ampache, созданное по инструкциям из руководства «Установка стека Linux, Apache, MySQL, PHP (LAMP) на Ubuntu 18.04», вы должны выключить его. Для выключения воспользуйтесь утилитой a2dissite:

      • sudo a2dissite test_virtalhost_file

      Создайте и откройте файл VirtualHost в текстовом редакторе в /etc/apache2/sites-available/ampache.conf:

      • sudo nano /etc/apache2/sites-available/ampache.conf

      Добавьте следующий шаблон VirtualHost в ваш файл:

      /etc/apache2/sites-available/ampache.conf

      <VirtualHost *:80>
      
          ServerName your_domain
          DocumentRoot /var/www/ampache
      
          <Directory /var/www/ampache/>
              AllowOverride All
              Require all granted
          </Directory>
      
          RewriteEngine on
          CustomLog /var/log/apache2/ampache.access.log common
          ErrorLog  /var/log/apache2/ampache.error.log
      
      </VirtualHost>
      

      Измените your_domain​​ на доменное имя, которое вы перенаправили на ваш сервер. После завершения сохраните файл и выйдите из редактора.

      Директивы в файле VirtualHost:

      • ServerName — доменное имя, которое Apache будет использовать для обслуживания вашего экземпляра Ampache.
      • DocumentRoot — местоположение файловой системы на вашем сервере с установленным экземпляром Ampache. Оно совпадает с местом распаковки ZIP-архива на шаге 1.
      • Directory — этот раздел передает конфигурацию в Apache, которая применяется ко всем файлам и директориям в составе пути.
      • RewriteEngine — позволяет выполнить перезапись модуля Apache.
      • CustomLog — создает файл журнала, который будет использовать Apache для записи всех сеансов доступа для вашего сервера Ampache.
      • ErrorLog — создает файл журнала, который будет использовать Apache для записи всех ошибок, создаваемых сервером Ampache.

      Используя утилиту apachecl, проверьте файл VirtualHost на отсутствие ошибок:

      • sudo apachectl configtest

      Если ошибки отсутствуют, после команды вы увидите следующий результат:

      Output

      Syntax OK

      Если в конфигурации содержатся ошибки, в результате будет указано имя файла и номер строки, где была обнаружена ошибка.

      Примечание. В случае обнаружения ошибки:

      AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
      

      Отредактируйте файл основной конфигурации Apache в /etc/apache2/apache2.conf и добавьте следующую строку:

      ServerName your_domain
      

      Активируйте новую конфигурацию VirtualHost с помощью утилиты a2ensite:

      Конечная конфигурация необязательна, но рекомендуется. По умолчанию в PHP нельзя загружать файлы размером, превышающим 2 Мб. Музыкальные файлы обычно имеют больший размер, поэтому увеличение значения по умолчанию позволит использовать интерфейс Ampache для загрузки файлов большего размера в вашу коллекцию музыки.

      Откройте /etc/php/7.2/apache2/php.ini с помощью следующей команды:

      • sudo nano /etc/php/7.2/apache2/php.ini

      Внесите изменения в следующие строки:

      /etc/php/7.2/apache2/php.ini

      . . .
      upload_max_filesize = 2M
      . . .
      post_max_size = 8M
      . . .
      

      До:

      /etc/php/7.2/apache2/php.ini

      . . .
      upload_max_filesize = 100M
      . . .
      post_max_size = 110M
      . . .
      

      Теперь вы сможете загружать музыкальный файлы размером до 100 Мб. Введите большее значение для загрузки файлов большего размера. Сохраните и закройте файл.

      Перезагрузите обновленную конфигурацию Apache:

      • sudo systemctl reload apache2.service

      Вы только что настроили Apache для обслуживания Ampache через HTTP. Далее вы получите сертификат TLS, произведете настройку Apache для защиты доступа к Ampache через HTTPS.

      Шаг 3 — Активация HTTPS

      На этом шаге вы получите бесплатный TLS сертификат Let’s Encrypt TLS с помощью утилиты Certbot, который активирует протокол HTTPS. Certbot создаст сертификат, автоматически сгенерирует требуемую конфигурацию для Apache и произведет автоматическое обновление сертификата.

      Это важно, поскольку при каждом входе в Ampache вы будете отсылать ваше имя пользователя и пароль через сеть Интернет. Если не использовать HTTPS, то незащищенный пароль можно будет прочесть во время его пересылки по сети Интернет.

      Релизы LTS для Ubuntu обычно не имеют последних пакетов, для этого используется программа Certbot. Разработчики Certbot создали репозиторий специально для Ubuntu, также известный как PPA, где пользователи Ubuntu имеют возможность скачать Certbot и выполнить ее обновление до последней версии.

      Установите репозиторий Certbot с помощью команды:

      • sudo add-apt-repository ppa:certbot/certbot

      Установите утилиту certbot:

      • sudo apt install python-certbot-apache

      Используйте утилиту Certbot для получения сертификата TLS:

      • sudo certbot --apache -d your_domain

      Опция --apache использует плагин Apache, позволяющий Certbot автоматически считывать и настраивать Apache. your_domain определяет доменное имя для которого Certbot создаст сертификат.

      При выполнении команды certbot вам будет предложено ответить на несколько вопросов. От вас попросят ввести адрес электронной почты и согласиться с условиями обслуживания.

      Если программа certbot успешно установит, что домен контролируется вами, она попросит вас произвести настройку HTTPS:

      Output

      Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access. ------------------------------------------------------------------------------- 1: No redirect - Make no further changes to the webserver configuration. 2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for new sites, or if you're confident your site works on HTTPS. You can undo this change by editing your web server's configuration. ------------------------------------------------------------------------------- Select the appropriate number [1-2] then [enter] (press 'c' to cancel):
      • No redirect​​​: Apache будет обслуживать Ampache через HTTP и HTTPS.
      • Redirect: Apache автоматически перенаправит любые соединения через HTTP на HTTPS. Это будет означать, что доступ к вашему серверу Ampache будет возможен только через HTTPS. Опция обеспечивает большую защиту и не влияет на работу вашего экземпляра Ampache. Рекомендуется сделать этот выбор.

      Убедитесь, что автоматическое обновление сертификата было успешно выполнено с помощью команды:

      • sudo certbot renew --dry-run

      Опция --dry-run означает, что certbot проверит попытку обновления без внесения постоянных изменений в ваш сервер. Если проверка пройдет успешно, в результате будет содержаться следующая строка:

      Output

      Congratulations, all renewals succeeded. The following certs have been renewed: /etc/letsencrypt/live/your_domain/fullchain.pem (success)

      Apache и PHP готовы к обслуживанию вашего экземпляра Ampache. На следующем шаге вы создадите и настроите базу данных Ampache.

      Шаг 4 — Создание базы данных MySQL

      Ampache использует базу данных MySQL для хранения различной информации, например, плейлистов, пользовательских настроек и т. д. На этом шаге вы создадите базу данных и пользователя MySQL, который будет иметь доступ к ней.

      Для создания базы данных Ampache вам необходимо предоставить следующую информацию:

      1. ampache_database: имя базы данных Ampache.
      2. database_user: пользователь MySQL, который будет использоваться Ampache для доступа к базе данных. Этот пользователь отличается от пользователя системы и имеет доступ только к базе данных.
      3. database_password: пароль пользователя базы данных. Убедитесь, что выбрали надежный пароль.

      Запомните указанную информацию, она понадобится вам позднее.

      Откройте интерактивную оболочку MySQL с помощью команды mysql:

      • mysql --user=root --password

      --user=root открывает оболочку MySQL от имени root user, а --password запрашивает пароль пользователя.

      Создайте пустую базу данных с помощью команды:

      • CREATE DATABASE ampache_database;

      Создайте пользователя MySQL:

      • CREATE USER 'database_user'@'localhost' IDENTIFIED BY 'database_password';

      Предоставьте новому пользователю полный доступ к базе данных:

      • GRANT ALL PRIVILEGES ON ampache_database.* TO 'database_user'@'localhost';

      Проверьте, что новая база данных была создана с помощью команды:

      Результат будет выглядеть следующим образом:

      +--------------------+
      | Database           |
      +--------------------+
      | information_schema |
      | ampache_database  |
      | mysql              |
      | performance_schema |
      | sys                |
      +--------------------+
      5 rows in set (0.00 sec)
      

      Выполните выход из оболочки MySQL с помощью команды exit;.

      Проверьте базу данных, имя пользователя и пароль путем входа в оболочку MySQL с database_user.

      Введите следующую команду для входа в оболочку MySQL в качестве нового пользователя:

      • mysql --user=database_user --password ampache_database

      Вы создали базу данных для использования Ampache. Вы закончили настройку сервера и готовы завершить процесс установки с помощью веб-установщика.

      Шаг 5 — Использование веб-установщика

      На этом шаге вы используете веб-установщик Ampache для завершения процесса установки и предоставления Ampache необходимой информации для работы, например, имени администратора веб-интерфейса, информации по базе данных и других настроек.

      Введите https://your_domain​​​ в ваш браузер для начала веб-установки.

      Выберите язык установки

      Выберите язык интерфейса Ampache и нажмите кнопку Start Configuration, чтобы продолжить.

      Требования

      На этой странице Ampache выполнит проверку соответствия сервера необходимым требованиям. Каждая строка страницы выполняет определенную проверку, например, проверку того, что все модули PHP присутствуют и находятся в рабочем состоянии. После того, как рядом с каждой проверкой появится галочка зеленого цвета, это будет означать, что ваш сервер готов к работе с Ampache.

      Нажмите Continue для перехода на следующую страницу.

      Вставка базы данных Ampache

      Если база данных Ampache отсутствует, то на этой странице она будет создана и отформатирована. Заполните следующие поля:

      • Требуемое имя базы данных: ampache_database
      • Имя хоста MySQL: localhost
      • Порт MySQL (необязательно):<EMPTY>
      • Имя администратора MySQL: database_user
      • Пароль администратора MySQL: database_password
      • Создайте базу данных:<UNCHECKED>
      • Создайте таблицы (ampache.sql):<CHECKED>
      • Создайте пользователя базы данных:<UNCHECKED>

      Изображение заполненной формы

      Нажмите кнопку Insert Database для продолжения.

      Создание файла конфигурации

      На этой странице создается файл конфигурации для использования Ampache. Заполните поля следующим образом:

      • Сетевой путь:<EMPTY>

      • Имя базы данных: ampache_database

      • Имя хоста MySQL: localhost

      • Порт MySQL Port (необязательно):<EMPTY>

      • Имя пользователя MySQL: database_user

      • Пароль MySQL: database_password

      Изображение заполненной формы

      • Тип установки Оставьте значение по умолчанию.

      • Разрешить транскодинг Выберите ffmpeg из выпадающего списка.

      • Проигрыватели Оставьте значения по умолчанию.

      Нажмите кнопку Create Config для продолжения.

      Создайте учетную запись администратора

      На этой странице создается главный пользователь веб-интерфейса. Этот пользователь будет обладать всеми административными правами и привилегиями, вы используете его для входа и первой настройки Ampache.

      Выберите имя пользователя и надежный пароль, введите пароль в поля Password и Confirm Password.

      Нажмите кнопку Create Account​​​ для продолжения.

      Обновление Ampache

      На этой странице можно внести любые необходимые административные изменения в базу данных Ampache. Изменения вносятся во время последующего обновления программы, так как установка была выполнена в первый раз, никаких изменений не будет.

      Нажмите кнопку Update Now!​​​ для продолжения.

      Обновление Ampache

      На этой странице отображаются и разъясняются все изменения, произведенные установщиком на предыдущем шаге. Для вас эта страница будет пустой.

      Пройдите по ссылке [Return to main page] для перехода на страницу входа в систему. Введите имя пользователя и пароль, которые были определены для входа на сервер Ampache.

      Для начала использования Ampache необходимо выполнить еще одну небольшую настройку. Настройка будет заключаться в добавлении музыки для вашего нового сервера Ampache.

      Шаг 6 — Добавление вашей музыки в Ampache

      Для начала использования сервера необходимо добавить музыкальные файлы. На этом шаге вы настроите каталог для музыки и загрузите в него несколько музыкальных файлов. “Каталог” – это имя, которое Ampache присваивает коллекции музыки. Ampache может загружать музыку как с сервера, так и из внешних источников, здесь вы загрузите и сохраните музыкальные файлы с сервера в локальный каталог Ampache.

      Пройдите по ссылке add a Catalog в следующей сроке на первой странице, которую вы увидите после входа в Ampache:

      Настройка Catalog еще не выполнена. Для начала потокового воспроизведения ваших медиа-файлов вам потребуется добавить Catalog.

      Для этого нужно перейти на страницу Add Catalog​​​. Заполните поля следующим образом:

      • Имя каталога“: присвойте каталогу короткое, запоминающееся имя.
      • Тип каталога: local
      • Шаблон имени файла:<EMPTY>
      • Шаблон папки: оставьте значение по умолчанию.
      • Gather Art:<CHECKED>
      • Создавать плейлисты из файлов плейлистов (m3u, m3u8, asx, pls, xspf):<UNCHECKED>
      • Путь: /data/Music

      Изображение завершенной формы добавления каталога

      Нажмите кнопку Add Catalog для завершения действий на этой странице.

      Нажмите кнопку Continue на следующей странице. На экране появится страница Show Catalogs​​​, где будет отображаться информация по созданному каталогу. Настройки каталога можно изменять в любое время.

      Включите утилиту веб-загрузки Ampache, нажав на третью навигационную иконку для доступа к расширенным настройкам:

      Изображение третьей иконки настроек

      Прокрутите вниз до раздела Server Config и пройдите по ссылке System для того, чтобы открыть страницу с системными настройками.

      Найдите строку Allow user uploads​​​​​ и выберите Enable из выпадающего меню в столбце Value.

      Вы также можете выбрать уровень пользователя для загрузки музыкальных файлов. Уровень по умолчанию Catalog Manager​​​, он позволяет всем пользователям уровня Catalog Manager и выше загружать музыку. В нашем случае это администратор.

      Также необходимо установить каталог для добавления музыкальных файлов. Определите его в строке Destination catalog. Выберите созданный каталог из выпадающего списка Value.

      Изображение строк разрешения на загрузку и каталога назначения

      Нажмите кнопку Update Preferences для завершения настройки конфигурации. Вы можете загрузить музыкальные файлы.

      Нажмите на первую иконку настроек:

      Изображение иконки первых настроек

      Пройдите по ссылке Upload в разделе Music.

      Изображение ссылки на загрузку

      Нажмите Browse на странице Upload, найдите музыкальные файлы на вашем компьютере и загрузите их.

      Если вы оставите ярлыки Artist и Album пустыми, Ampache будет автоматически считывать ID3 теги музыкальных файлов, чтобы определить исполнителя и название альбома. После загрузки музыкальных файлов их можно будет найти с помощью ссылок Songs, Albums или Artists в разделе Music на навигационной панели слева.

      Ваш музыкальный сервер Ampache готов к потоковому воспроизведению музыки.

      Заключение

      В этой статье вы научились устанавливать и настраивать сервер потоковой трансляции музыки Ampache и загружать музыкальные файлы. Вы можете начать прослушивание музыки в любом месте, где бы вы не были, на любом из ваших устройств. Дополнительная информация по использованию и расширенным возможностям вашего сервера потоковой трансляции музыки находится в Документации Ampache. Эти приложения Android и эти приложения iOS можно использовать для потоковой трансляции музыки на ваш телефон. Ampache организует вашу музыку на сервере с помощью ID3 тегов в музыкальных файлах. Программа MusicMrainz поможет вам управлять ID3 тегами ваших музыкальных файлов.



      Source link

      How To Install the Ampache Music Streaming Server on Ubuntu 18.04


      The author selected Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Ampache is an open-source music streaming server that allows you to host and manage your digital music collection on your own server. Ampache can stream your music to your computer, smartphone, tablet, or smart TV. This means that you don’t have to maintain multiple copies of your music on the device you want to use to listen to it. With Ampache you can manage your collection on your server using Ampache’s web interface and listen to it anywhere.

      In this tutorial, you will install and configure the Apache webserver and PHP that will serve your Ampache instance. You will then create a MySQL database that Ampache will use to store all of its operational information. Finally you will upload your music collection so you can start streaming your music.

      Prerequisites

      Before you begin this guide you’ll need the following:

      Step 1 — Installing Ampache

      In this step, you will download the Ampache ZIP archive to your server, unpack it to its installation home directory, and make some necessary file system changes.

      First, log in to your server as the non-root user. Then create Ampache’s home directory with the following command:

      • sudo mkdir /var/www/ampache

      Next, install the zip utility that you will need to unpack the Ampache archive:

      Next, download the ZIP archive of the latest release. You can find the link to the latest release on Ampache’s GitHub page. In these examples, version 4.1.1 is used:

      • wget https://github.com/ampache/ampache/releases/download/4.1.1/ampache-4.1.1_all.zip

      Next, unpack the ZIP archive into the /var/www/ampache/ directory using the -d option:

      • sudo unzip ampache-4.1.1_all.zip -d /var/www/ampache/

      Next, set the user and group identity of Ampache’s files so that Apache is able to read, write, and execute the Ampache instance files:

      • sudo chown --recursive www-data:www-data /var/www/ampache/

      The --recursive option makes chown change the ownership and group identity of all the files and subdirectory under /var/www/ampache/ to Apache’s user and group www-data.

      Next, rename the .htaccess files that are included in the ZIP archive. .htaccess files contain security and other operation information for Apache but they will only work with the file extension name .htaccess. Rename the supplied .htaccess.dist files to .htaccess with the following commands:

      • sudo mv /var/www/ampache/rest/.htaccess.dist /var/www/ampache/rest/.htaccess
      • sudo mv /var/www/ampache/play/.htaccess.dist /var/www/ampache/play/.htaccess
      • sudo mv /var/www/ampache/channel/.htaccess.dist /var/www/ampache/channel/.htaccess

      Now you’ll create the directory that will contain your music files. For security reasons, this directory is best created outside of Ampache’s installation directory. That way, it will not be readable or changeable by malicious web requests as it resides outside of Ampache’s DocumentRoot.

      Create the directory, /data/Music, with the following command:

      • sudo mkdir -p /data/Music

      Then change its owner and group identity so that Apache can read and write to it:

      • sudo chown www-data:www-data /data/Music

      To finish setting up, you’ll install FFmpeg, which is a utility that converts audio and video from one format to another. For example, you could use it to convert an MP3 music file to an OPUS music file. Ampache uses FFmpeg to convert audio on the fly from the format in which it was uploaded to a format that the listening device can play. This is a process known as transcoding.

      This is useful because not all devices are able to play all formats of music. Ampache can detect what formats are supported on the playing device and automatically supply your music in the supported format.

      Install FFmpeg with the following command:

      You’ve now unpacked and prepared your Ampache instance for the web installer and installed the FFmpeg utility. Next you’ll configure Apache and PHP to serve your Ampache instance.

      Step 2 — Configuring Apache and PHP

      In this section, you will configure Apache by creating a new VirtualHost file, which will provide the configuration that Apache needs to serve your Ampache server domain. You will also install some additional PHP modules that extend the abilities of PHP to cover the requirements of Ampache

      First, install some additional PHP modules that were not included with the default PHP installation:

      • sudo apt install php-mysql php-curl php-json php-gd php7.2-xml

      These modules provide the following additional functionality:

      • php-mysql — Enables PHP to communicate with a MySQL database.
      • php-curl — Enables PHP to use the curl utility to download files, such as album cover art, from remote servers.
      • php-json — Enables PHP to read and manipulate JSON formatted text files.
      • php-gd — Enables PHP to manipulate and create image files.
      • php7.2-xml — Enables PHP to read and manipulate XML formatted text files.

      Next, enable a couple of Apache modules using the a2enmod utility:

      • sudo a2enmod rewrite expires

      These Apache modules allow Apache to do the following:

      • rewrite — Modify or rewrite URLs following rules supplied by Ampache.
      • expires — Set the cache expiry times for objects such as images so that they are more efficiently stored by browsers.

      Now, you will create the VirtualHost file that tells Apache how and where to load the Ampache instance.

      Note: If you created a test VirtualHost file that uses your Ampache domain name when you followed the “How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu 18.04” guide you must disable it. Use the a2dissite utility to disable it:

      • sudo a2dissite test_virtalhost_file

      Now, create and open the VirtualHost file with your text editor at /etc/apache2/sites-available/ampache.conf:

      • sudo nano /etc/apache2/sites-available/ampache.conf

      Add the following VirtualHost template into your file:

      /etc/apache2/sites-available/ampache.conf

      <VirtualHost *:80>
      
          ServerName your_domain
          DocumentRoot /var/www/ampache
      
          <Directory /var/www/ampache/>
              AllowOverride All
              Require all granted
          </Directory>
      
          RewriteEngine on
          CustomLog /var/log/apache2/ampache.access.log common
          ErrorLog  /var/log/apache2/ampache.error.log
      
      </VirtualHost>
      

      You must change your_domain to the domain name that you redirected to your server. When you have finished editing this file save and exit the editor.

      The directives in this VirtualHost file are:

      • ServerName — The domain name that Apache will use to serve your Ampache instance.
      • DocumentRoot — The file system location on your server where the Ampache instance is located. This is the same place that you unpacked the ZIP archive to in Step 1.
      • Directory — This section passes configuration to Apache that applies to the files and directories contained in the path.
      • RewriteEngine — Enables the rewrite Apache module.
      • CustomLog — Creates a log file that Apache will use to record all access logs for your Ampache server.
      • ErrorLog — Creates a log file that Apache will use to record all error logs generated by your Ampache server.

      Next, check that the VirtualHost file you created does not have any errors with the apachectl utility:

      • sudo apachectl configtest

      If your configuration does not contain any errors, you will see the following output after the command:

      Output

      Syntax OK

      If your configuration does contain errors, the output will print the file name and line number where the error was encountered.

      Note: If you see the error:

      AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
      

      Then you will need to edit Apache’s main configuration file at /etc/apache2/apache2.conf and add the following line:

      ServerName your_domain
      

      Next, enable the new VirtualHost configuration using the a2ensite utility:

      The final configuration is optional, but recommended. The default setting for file uploads in PHP is that no file greater than 2MB can be uploaded. Music files tend to be larger than this so increasing this size will allow you to use the Ampache interface to upload larger files in your music collection.

      Open /etc/php/7.2/apache2/php.ini with the following command:

      • sudo nano /etc/php/7.2/apache2/php.ini

      And change the following lines:

      /etc/php/7.2/apache2/php.ini

      . . .
      upload_max_filesize = 2M
      . . .
      post_max_size = 8M
      . . .
      

      To:

      /etc/php/7.2/apache2/php.ini

      . . .
      upload_max_filesize = 100M
      . . .
      post_max_size = 110M
      . . .
      

      You will now be able to upload music files up to 100MB. Use a larger value if you intend to upload files larger than this size. Save and exit the file.

      Finally, reload your updated Apache configuration:

      • sudo systemctl reload apache2.service

      You’ve now configured Apache to serve Ampache over HTTP. Next you’ll obtain a TLS certificate and configure Apache to use it so you can securely access Ampache over HTTPS.

      Step 3 — Enabling HTTPS

      In this step, you will get a free Let’s Encrypt TLS certificate using the Certbot utility, which enables HTTPS browsing. Certbot will create the certificate, automatically generate the required Apache configuration, and manage the automatic renewal of the certificate.

      This is important because every time you log in to Ampache you will send your username and password across the internet. If you are not using HTTPS then your password will be sent in plain text that can be read as it travels across the internet.

      Ubuntu’s LTS releases tend not to have the latest packages and this is true of the Certbot program. The Certbot developers maintain a dedicated Ubuntu repository, known as a PPA, so that Ubuntu users can keep an up-to-date copy of the Certbot.

      Install the Certbot repository with the following command:

      • sudo add-apt-repository ppa:certbot/certbot

      Now, install the certbot utility:

      • sudo apt install python-certbot-apache

      Next, use certbot to get the TLS certificate:

      • sudo certbot --apache -d your_domain

      The --apache option uses the Apache plugin that enables Certbot to read and configure Apache automatically. -d your_domain specifies the domain name for which you want Certbot to create the certificate.

      When you run the certbot command you will be asked a series of questions. You’ll be prompted to enter an email address and agree to the terms of service.

      If certbot successfully confirms that you control your domain, it will ask you to configure your HTTPS settings:

      Output

      Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access. ------------------------------------------------------------------------------- 1: No redirect - Make no further changes to the webserver configuration. 2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for new sites, or if you're confident your site works on HTTPS. You can undo this change by editing your web server's configuration. ------------------------------------------------------------------------------- Select the appropriate number [1-2] then [enter] (press 'c' to cancel):
      • No redirect: Apache will serve Ampache via HTTP and HTTPS.
      • Redirect: Apache will redirect any HTTP connections to HTTPS automatically. This means that your Ampache server will only be available via HTTPS. This option is the more secure and will not affect how your Ampache instance behaves. This is the recommended choice.

      Finally, test that the auto-renewal of the certificate will take place successfully by running the following command:

      • sudo certbot renew --dry-run

      The --dry-run option means that certbot will test a renewal attempt without making any permanent changes to your server. If the test was successful the output will include the following line:

      Output

      Congratulations, all renewals succeeded. The following certs have been renewed: /etc/letsencrypt/live/your_domain/fullchain.pem (success)

      Apache and PHP are now ready to serve your Ampache instance. In the next step, you will create and configure Ampache’s database.

      Step 4 — Creating a MySQL Database

      Ampache uses a MySQL database to store information such as playlists, user preferences, and so on. In this step, you will create a database and MySQL user that Ampache will use to access it.

      You will need to choose three pieces of information to complete the following instructions to create Ampache’s database:

      1. ampache_database: The name of the Ampache database.
      2. database_user: The MySQL user that Ampache will use to access the database. This is not a system user and can only access the database.
      3. database_password: The database user’s password. Be sure to choose a secure password.

      Make a note of these details as you will need them later.

      First, open the interactive MySQL shell with the mysql command:

      • mysql --user=root --password

      --user=root opens the MySQL shell as the MySQL root user and --password prompts for the root user’s password.

      The following command will create an empty database:

      • CREATE DATABASE ampache_database;

      Next, create the MySQL user:

      • CREATE USER 'database_user'@'localhost' IDENTIFIED BY 'database_password';

      Now, give the new user full access to the database:

      • GRANT ALL PRIVILEGES ON ampache_database.* TO 'database_user'@'localhost';

      Finally, check that the new database exists by running the following command:

      You will see the following output:

      +--------------------+
      | Database           |
      +--------------------+
      | information_schema |
      | ampache_database  |
      | mysql              |
      | performance_schema |
      | sys                |
      +--------------------+
      5 rows in set (0.00 sec)
      

      Exit the MySQL shell by entering exit;.

      Finally, test the database, username, and password by trying to log in to the MySQL shell with the database_user.

      Enter the following command to log in to the MySQL shell as the new user:

      • mysql --user=database_user --password ampache_database

      You’ve now created the database that Ampache will use. You’ve finished your server configuration and are ready to complete the installation with the web installer.

      Step 5 — Using the Web Installer

      In this step, you will use Ampache’s web installer to finish the installation by giving Ampache the information it will need to run, such as a web interface admin user, the database details, and other settings.

      Start the web installation by entering https://your_domain into your browser.

      Choose Installation Language

      Select Ampache’s interface language and click the Start Configuration button to continue.

      Requirements

      This page is where Ampache checks that the server meets its requirements. Each line on this page represents a test that the installer performs to ensure that, for example, all the required PHP modules are present and working. You’ll see every test has a green checkmark to indicate that your server is ready for Ampache.

      Click the Continue button to move on to the next page.

      Insert Ampache Database

      This page creates Ampache’s database if it does not exist and formats it. Fill in the fields as follows:

      • Desired Database Name: ampache_database
      • MySQL Hostname: localhost
      • MySQL Port (optional): <EMPTY>
      • MySQL Administrative Username: database_user
      • MySQL Administrative Password: database_password
      • Create Database: <UNCHECKED>
      • Create Tables (ampache.sql): <CHECKED>
      • Create Database User: <UNCHECKED>

      Image showing the completed form

      Click the Insert Database button to continue.

      Generate Configuration File

      This page creates the configuration file that Ampache will use to run. Fill in the fields as follows:

      • Web Path: <EMPTY>

      • Database Name: ampache_database

      • MySQL Hostname: localhost

      • MySQL Port (optional): <EMPTY>

      • MySQL Username: database_user

      • MySQL Password: database_password

      Image showing the completed form

      • Installation Type
        Leave this at the default setting.

      • Allow Transcoding
        Select ffmpeg from the drop-down list.

      • Players
        Leave these at the default settings.

      Click the Create Config button to continue.

      Create Admin Account

      This page creates the first web interface user. This user is created with full administrative, privileges and is the one that you will use to log in and configure Ampache for the first time.

      Choose a username and a secure password and enter it into the Password and Confirm Password fields.

      Click the Create Account button to continue.

      Ampache Update

      This page will perform any administrative changes to Ampache’s database that need making. These changes are made during version upgrades but as this is a new installation the installer will not make any changes.

      Click the Update Now! button to continue.

      Ampache Update

      This page prints and explains any updates that the installer made in the previous step. You should not see any updates listed.

      Click the [Return to main page] link to continue to the login page. Enter your username and password you set to log in to your Ampache server.

      Ampache is not quite fully set up and ready for use. You’ll now complete the setup by adding your music so you can start using your new Ampache server.

      Step 6 — Adding Your Music to Ampache

      A music server is no use without some music to play. In this step, you will configure a music catalog and upload some music. “Catalog” is the name that Ampache gives to a collection of music. Ampache is able to read music from many sources both on and off the server but in this tutorial, you will upload and store your music on the server in a local catalog, as Ampache refers to it.

      First, click the add a Catalog link in the following line on the first page that you see when you log in to Ampache:

      No Catalog configured yet. To start streaming your media, you now need to add a Catalog.

      This will take you to the Add Catalog page. Fill in the fields as follows:

      • Catalog Name: Give this catalog a short, memorable name.
      • Catalog Type: local
      • Filename Pattern: <EMPTY>
      • Folder Pattern: Leave this with the defaults.
      • Gather Art: <CHECKED>
      • Build Playlists from Playlist Files. (m3u, m3u8, asx, pls, xspf): <UNCHECKED>
      • Path: /data/Music

      Image showing the completed add catalog form

      Click the Add Catalog button to complete this page.

      On the page that follows click the Continue button. This will take you to the Show Catalogs page that will print the details for the catalog you created. You can change the catalog settings at any time in the future.

      Now, enable Ampache’s web upload facility by clicking on the third navigation icon to open the extended settings:

      Image showing the third settings icon

      Scroll down to the Server Config section and click the System link to open the system settings page.

      Find the Allow user uploads line and select Enable from the drop-down menu in the Value column.

      You can also choose what level of user is able to upload music files. The default level is Catalog Manager, this allows the Catalog Manager and all users with greater privileges to upload music. In this case, that is the administrator.

      You also need to set the catalog to which the music will get added. Set this using the Destination catalog line. Select the catalog you created in the Value drop-down.

      Image showing the allow upload and destination catalog lines

      Click the Update Preferences button at the bottom of the page to complete the configuration. You are now ready to upload some music.

      First, click the first settings icon:

      Icon showing the first settings icon

      Then click the Upload link in the Music section.

      Image showing upload link

      On the Upload page, click the Browse button and locate your music files on your computer and upload them.

      If you leave the Artist and Album labels blank then Ampache will read the ID3 tags of the music files to discover the artist and album automatically. After you have uploaded some music you will now be able to find it by clicking on the Songs, Albums, or Artists links in the Music section in the navigation panel on the left.

      Your Ampache music server is now ready to start streaming your music.

      Conclusion

      In this article, you installed and configured an Ampache music streaming server and uploaded some of your music. You can now listen to your music wherever you go on any of your devices. Ampache’s Documentation will help you use and extend your streaming server. These Android apps and this iOS app will stream your music to your phone. Ampache organizes your music on the server using the ID3 tags in the music files. The MusicMrainz program will help you manage the ID3 tags of your music files.



      Source link