专题四 在Cisco Packet Tracer中制作音乐播放器(多个音乐播放)

一. 任务要求:

        在 sound_frequency_detector.pkt 的基础上,修改成可以播放三首音乐。

二. 设计思路:

        2.1 首先,将音频文件放到软件目录下的sounds文件夹中并修改代码中的路径。

         2.2 更改代码中更新歌曲状态的部分,让其能完整播放音频文件并实时检测是否切歌,并显示当前是哪一首歌。

 #播放选中的音乐 
    if -1 is not g_currSound:
        playSound(g_sounds[g_currSound].soundID,1)
        
        if g_currSound == 0:
        	xuhao ="first"
        elif g_currSound == 1:
        	xuhao ="secound"
        elif g_currSound == 2:
        	xuhao ="third"
        print("playing "+xuhao+" music...")
        
        for i in range(play_time[g_currSound]):
        	sleep(1)
        	IoEClient.reportStates(g_currSound)
        	setDeviceProperty(getName(), "Signal", g_currSound)
        	updateEnvironment()
        	if i == play_time[g_currSound]-1:
				print("playing time over...")
				break
			#检查旋钮转度
        	playValue = 255*(analogRead(A0)/1023.0)
        	if 0 == playValue:
        		stopSound(g_sounds[g_currSound].soundID)
        		print("stop playing...")
        		g_currSound = -1
        		break
        	else:
    			g_currSound1 = int((playValue-1) / (255./len(g_sounds)))
    			if(g_currSound1==g_currSound):
    				continue
    			else:
    				#关闭上一个音乐
    				if g_currSound1 != -1:
    					stopSound(g_sounds[g_currSound].soundID)
    				g_currSound=g_currSound1
    				print("playing next...")
    				break

       本段代码分析:

        首先,在开头判断当前音乐序号 g_currSound是否为“-1”,若是,则不能播放音乐,反之播放音乐并判断是哪一首音乐。

        接下来,在for循环中用sleep()函数累计歌曲的时长,歌曲时长提前保存在play_time中。

        若循环到播放完毕,则从头开始;若在播放过程中,检测到旋钮发生变化,则首先判断是否为关闭,若是则停止播放,否则播放对应音乐,若在本音乐的播放区间中,则无变化。

        值得注意的是,若要切换歌曲必须关闭上一个歌曲,否则会叠加buff,耳朵好的可以试试!

三.运行结果

关闭时
关闭后
开启后
开启后

 四. 完整代码:

from time import *
from physical import *
from gpio import *
from environment import Environment
from ioeclient import IoEClient
from pyjs import *

VOLUME_AT_RATE = 100000
SOUND_VOLUME = 65
SOUND_PITCH = 20
SOUND_WHITE_NOISE = 20
play_time=(278,270,300)

#家庭扬声器,可播放多种预定义声音之一
g_sounds = [JsObject({"soundID": 'sound1', "soundPath": '/../Sounds/01.wav'}),
            JsObject({"soundID": 'sound2', "soundPath": '/../Sounds/02.wav'}),
            JsObject({"soundID": 'sound3', "soundPath": '/../Sounds/03.wav'})]
            
#当前音乐编号 
g_currSound = -1;

# 设置主扬声器。停止所有旧声音并添加要使用的声音
def setup():
    global g_currSound
    #c初始化SOUND_dB
    setDeviceProperty(getName(), 'SOUND_dB', 0)

    IoEClient.setup ({
    "type": 'Home Speaker',
    "states": [{
        "name": 'Signal',
        "type": 'number',
        "controllable": False
        }]
    })
    #清空 
    destroySounds()
    #加载歌单
    for ind in xrange(0 ,len(g_sounds)):        # var ind
        addSound(g_sounds[ind].soundID, g_sounds[ind].soundPath)
    #SOUND_dB当前属性默认值
    restoreProperty("SOUND_dB", 0)
    #Signal当前属性默认值
    g_currSound = restoreProperty("Signal", -1)

#恢复属性(属性名称,默认值)
def restoreProperty (propertyName, defaultValue):
	#先获取 
    value = getDeviceProperty(getName(), propertyName)
    #判断是否存在  
    if  not (value is "" or value == "undefined" or value == None) :
    	#判断值的类型 
        if  isinstance(defaultValue, (int, float)):
            value = int(value)
        #设置属性 
        setDeviceProperty(getName(), propertyName, value)
        return value
    return defaultValue

#更新功能。每次更新调用一次。
def loop():
    updateState()
    delay(1000);

#更新歌曲状态,从歌单中读取并播放合适的声音
def updateState():
	
    global g_currSound
    
    #获取旋钮转度
    playValue = 255*(analogRead(A0)/1023.0)
    
    #限制上下限
    if 0 > playValue:
        playValue = 0
    elif playValue > 255:
        playValue = 255
    
    #更新SOUND_dB:属性值
    setDeviceProperty(getName(), 'SOUND_dB', int(playValue * (60/255)))
    
    #关闭上一个音乐
    if -1 != g_currSound:
        stopSound(g_sounds[g_currSound].soundID)
        
    #检查旋钮转度
    if 0 == playValue:
        g_currSound = -1
        print("stop playing...")
    else:
        g_currSound = int((playValue-1) / (255./len(g_sounds)))
        
    #播放选中的音乐 
    if -1 is not g_currSound:
        playSound(g_sounds[g_currSound].soundID,1)
        
        if g_currSound == 0:
        	xuhao ="first"
        elif g_currSound == 1:
        	xuhao ="secound"
        elif g_currSound == 2:
        	xuhao ="third"
        print("playing "+xuhao+" music...")
        
        for i in range(play_time[g_currSound]):
        	sleep(1)
        	IoEClient.reportStates(g_currSound)
        	setDeviceProperty(getName(), "Signal", g_currSound)
        	updateEnvironment()
        	if i == play_time[g_currSound]-1:
				print("playing time over...")
				break
			#检查旋钮转度
        	playValue = 255*(analogRead(A0)/1023.0)
        	if 0 == playValue:
        		stopSound(g_sounds[g_currSound].soundID)
        		print("stop playing...")
        		g_currSound = -1
        		break
        	else:
    			g_currSound1 = int((playValue-1) / (255./len(g_sounds)))
    			if(g_currSound1==g_currSound):
    				continue
    			else:
    				#关闭上一个音乐
    				if g_currSound1 != -1:
    					stopSound(g_sounds[g_currSound].soundID)
    				g_currSound=g_currSound1
    				print("playing next...")
    				break
    


def updateEnvironment():
    volumeRatio = VOLUME_AT_RATE / Environment.getVolume()
    if g_currSound >= 0:
        Environment.setContribution("Sound Volume", SOUND_VOLUME*volumeRatio, SOUND_VOLUME*volumeRatio, False)
        Environment.setContribution("Sound Pitch", SOUND_PITCH*(g_currSound+1), SOUND_PITCH*(g_currSound+1), False)
        Environment.setContribution("White Noise", SOUND_WHITE_NOISE, SOUND_WHITE_NOISE, False)
    else:
        Environment.setContribution("Sound Volume", 0, 0, False)
        Environment.setContribution("Sound Pitch", 0, 0, False)
        Environment.setContribution("White Noise", 0, 0, False)

if __name__ == "__main__":
    setup()
    while True:
        loop()
        sleep(1)

 pkt附件下载(可直接运行):

3.1.rar - 蓝奏云(密码请关注公众号:玹之空间-->资料获取)

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值