• python 模拟(简易)音乐播放器


    模拟一个在线音乐播放程序
    # 1, 使用C/S架构来进行设计,分别写出客户端和服务器程序

    # 2,客户端链接服务器之后,服务器向用户提示可以选择的歌曲列表,用户选择后开始播放(音频文件存放在本地即可)

     #思路是通过socketserver ,客户端发送指令到服务端,服务端连接数据库查到歌曲名字路径返回给客户端,客户端通过pygame模块查找到歌曲路径 播放歌曲

    #创建数据表,插入歌曲名字和路径

    CREATE TABLE t_music(
    id INT PRIMARY KEY AUTO_INCREMENT,
    NAME VARCHAR(32),
    path VARCHAR(32)
    )
    SELECT * FROM t_music
    INSERT INTO t_music(NAME,path) VALUE("味道","D:\\老男孩\\味道.mp3"),("世间美好与你环环相扣","D:\\老男孩\\世间美好与你环环相扣.mp3")

    服务端:

    import pymysql
    import json
    import socketserver
    class MyServer(socketserver.BaseRequestHandler):
    @classmethod
    def conn(cls,name):
    conn = pymysql.connect(host="localhost", user="root", password="123456", db="music", charset="utf8")
    cur = conn.cursor()
    sql = "select path from t_music where name='%s'" % name
    cur.execute(sql)
    data = cur.fetchall()
    return data
    @classmethod
    def conn2(cls):
    conn = pymysql.connect(host="localhost", user="root", password="123456", db="music", charset="utf8")
    cur = conn.cursor()
    sql = "select name from t_music"
    cur.execute(sql)
    data = cur.fetchall()
    mydic = {}
    lst = []
    for i in data:
    for j in i:
    print(i[0])
    lst.append(i[0])
    for k, v in enumerate(lst):
    mydic[k] = v
    a = json.dumps(mydic)
    return a
    def handle(self):
    while True:
    data = self.request.recv(1024)
    print('->client',data)
    if data.decode() == 'a':
    # pass
    self.request.send(self.conn2().encode())
    else:
    self.request.send(self.conn(data.decode())[0][0].encode())

    socketserver.TCPServer.allow_reuse_address = True
    server = socketserver.ThreadingTCPServer(('127.0.0.1', 8080), MyServer)
    server.serve_forever()
    客户端:
    import socket
    import json
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect(('127.0.0.1', 8080))
    def broadcast(): # broadcast播放
    import pygame
    import time
    pygame.mixer.init() #初始化
    pygame.mixer.music.load(data1) # 通过路径path 加载
    pygame.mixer.music.play() #在程序运行中会播放
    # print("正在播放的歌曲:%s" % name)
    time.sleep(100) #让程序保持运行状态

    while True:
    name =input("请输入a获取歌曲列表或歌曲名字播放:")
    client.send(name.encode('utf-8'))
    data1 = client.recv(1024).decode('utf-8')
    if name =='a':
    data2 =json.loads(data1)
    print(data2)
    else:
    print(data1)
    broadcast()
    #使用 mixer 播放音效
    #山楂树之恋 世间美好与你环环相扣 味道


    人生苦短,我用python
  • 相关阅读:
    iptables学习笔记
    启动级别和单用户模式
    Apache虚拟主机配置模板
    LAMP环境搭建问题
    LAMP环境搭建
    C++面向对象高级编程(九)Reference与重载operator new和operator delete
    C++面向对象高级编程(八)模板
    C++面向对象高级编程(七)point-like classes和function-like classes
    C++面向对象高级编程(六)转换函数与non-explicit one argument ctor
    C++面向对象高级编程(五)类与类之间的关系
  • 原文地址:https://www.cnblogs.com/niucunguo/p/12202991.html
Copyright © 2020-2023  润新知