Preface
environment:
Python
Problem description:
How to play local music in Python and play on web pages
Solution:
To play local music in Python and play in web pages, you can use two different methods: one is to play audio files in Python on the server side, and the other is to create a web application that plays audio files in the client side through the <audio> tag of HTML5. I will introduce these two methods below.
Method 1: Play local music using Python
If you just want to play local music files on the server side (for example in a development environment), you can use Python's third-party libraries such as pydub or simpleaudio. Take playsound as an example here, which is a simple and easy-to-use library:
Installation dependencies
pip install playsound
Play local music
from playsound import playsound # Replace with your audio file pathaudio_file = "path/to/your/audio.mp3" playsound(audio_file)
This approach is suitable for situations where audio needs to be played on the server side or in a command line environment, but is not suitable for web applications.
Method 2: Play local music in a web page
In order to play local music files in a web page, you need to create a web application and use the HTML5 <audio> tag to embed the audio file. Python can be used to create this web application, such as using frameworks such as Flask or Django.
Create simple web applications with Flask
Step 1: Install Flask
pip install Flask
Step 2: Create a Flask application
Create a new Python file and add the following code:
from flask import Flask, render_template app = Flask(__name__) @('/') def index(): return render_template('') if __name__ == '__main__': (debug=True)
Step 3: Create an HTML template
Create a folder named templates in the project directory and create a file named . In this file, use the HTML5 <audio> tag to embed the audio file:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Play Local Music</title> </head> <body> <h1>Play Local Music File</h1> <audio controls> <source src="{{ url_for('static', filename='music/sample.mp3') }}" type="audio/mpeg"> Your browser does not support the audio element. </audio> </body> </html>
Step 4: Add a static file
Create a folder named static in the project directory and place your audio file (such as sample.mp3) in this folder.
Step 5: Launch the application
Run the following command in the terminal to start the Flask application:
python
Visit http://127.0.0.1:5000/ and you should be able to see the audio controls in your browser and play the audio file.
Summarize
Server-side playback: If you only need to play audio files on the server, you can use Python's third-party library such as playsound.
Web page playback: If you need to play audio files in a web page, it is recommended to use the HTML5 <audio> tag and combine Flask or other web frameworks to create web applications.
Choosing the right method depends on your specific needs. If you have any further questions or need more help, feel free to let me know!
Voice song order
How to call songs by voice, start Python to play local music and link front-end js to play on web pages?
In order to implement the voice song function, start Python to play local music and link front-end JavaScript to play on the web page, you need to combine multiple components and technologies to build a complete solution. This plan will include the following parts:
- Voice recognition: Receive user voice input and convert it into text.
- Song selection logic: Select the corresponding song file based on the recognized text.
- Server-side processing: Use Python to process the request and send the audio file path to the front-end.
- Front-end display and control: Use HTML and JavaScript to display and control audio playback.
Technology stack
Backend: Python (Flask or Django)
Front-end: HTML, CSS, JavaScript
Voice Recognition: You can use the SpeechRecognition library or integrate third-party APIs (such as Google Speech-to-Text)
Audio playback: HTML5 <audio> tag
Implementation steps
1. Set up the Flask application
First, install the necessary dependency library:
pip install Flask SpeechRecognition pydub
Create a file named , to build a Flask application:
from flask import Flask, render_template, request, jsonify import speech_recognition as sr import os app = Flask(__name__) # Assume that your music files are stored in the static/music folderMUSIC_DIR = 'static/music' music_files = {(f)[0]: f for f in (MUSIC_DIR) if ('.mp3')} @('/') def index(): return render_template('') @('/recognize', methods=['POST']) def recognize(): recognizer = () audio_file = ['audio'] with (audio_file) as source: audio_data = (source) try: text = recognizer.recognize_google(audio_data, language='zh-CN') print("Recognized Text:", text) # Simple match song title song_name = next((key for key in music_files.keys() if key in text), None) if song_name: return jsonify({'status': 'success', 'song': song_name}) else: return jsonify({'status': 'not_found'}) except : return jsonify({'status': 'error', 'message': 'Can't understand the audio'}) except as e: return jsonify({'status': 'error', 'message': f'Request error: {e}'}) if __name__ == '__main__': (debug=True)
2. Create HTML and JavaScript files
Create a file in the templates folder:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Voice song ordering system</title> <script src="/npm/@tensorflow/tfjs"></script> <script> async function recognizeSpeech() { const recognition = new ( || )(); = 'zh-CN'; = false; = 1; return new Promise((resolve, reject) => { = event => { const transcript = [0][0].transcript; resolve(transcript); }; = error => { reject(error); }; (); }); } async function playSong() { const transcript = await recognizeSpeech(); ("Transcribed Text:", transcript); const response = await fetch('/recognize', { method: 'POST', body: new FormData(), headers: { 'Content-Type': 'multipart/form-data' } }); const data = await (); if ( === 'success') { ('audioPlayer').src = `/static/music/${}.mp3`; ('audioPlayer').play(); } else { alert('This song was not found'); } } </script> </head> <body> <h1>Voice song ordering system</h1> <button onclick="playSong()">Start ordering songs</button> <audio controls></audio> </body> </html>
3. Add static resources
Make sure your music files are placed in the static/music folder, such as static/music/sample.mp3.
4. Run the application
Run the following command in the terminal to start the Flask application:
python
Visit http://127.0.0.1:5000/, you should be able to see a button, clicking it will start speech recognition, and then play the corresponding music file according to the recognition results.
Things to note
Voice recognition accuracy: In practical applications, you may need more complex logic to improve the accuracy of voice recognition, such as using natural language processing technology for intent analysis.
Security: Pay attention to security issues when uploading audio files to prevent malicious files from being uploaded.
Performance Optimization: For large music libraries, consider using a database to store metadata and quickly find songs through indexes.
User experience: User experience can be improved through the front-end interface, such as adding search history, recommended songs and other functions.
Through the above steps, a basic voice lyrics system can be built, where Python is responsible for back-end processing and speech recognition, while the front-end controls audio playback through HTML and JavaScript.
The above is the detailed content of how Python can play local music and play on web pages. For more information about Python playing local music, please follow my other related articles!