python极客项目编程第四章实验

AI权益加码!Claude Code、Cursor等20+工具免费用! 购周边限时加赠Coding Plan Lite,畅享主流AI工具!学习进阶更高效! 阅读详情

第一问

Use the techniques you learned in this chapter to create a method that replicates the sound of two strings of different frequencies vibrating together. Remember, the Karplus-Strong algorithm produces sound amplitudes that can be added together (before scaling to 16-bit values for WAV file creation). Now add a time delay between the first and second string plucks.

import math
import wave

import numpy as np


def together(a, b, t=0):
    sRate = 44100
    nSamples = sRate * 5
    x = np.arange(nSamples)/float(sRate)
    vals1 = np.sin(2.0*math.pi*a*x + t)
    vals2 = np.sin(2.0*math.pi*b*x)

    vals = vals1 + vals2
    data = np.array(vals * 32767, 'int16').tobytes()

    file = wave.open('together.wav', 'wb')
    file.setparams((1, 2, sRate, nSamples, 'NONE', 'uncompressed'))
    file.writeframes(data)
    file.close()


if __name__ == '__main__':
    together(200, 400, 0.01)

第二问

  1. Write a method to read music from a text file and generate musical notes. Then play the music using these notes. You can use a format where the note names are followed by integer rest time intervals, like this: C4 1 F4 2 G4 1 . . . .
import random
import time

import pygame


# play a wav file
class NotePlayer:
    # constr
    def __init__(self):
        pygame.mixer.pre_init(44100, -16, 1, 2048)
        pygame.init()
        # dictionary of notes
        self.notes = {}

    # add a note
    def add(self, fileName):
        self.notes[fileName] = pygame.mixer.Sound(fileName)

    # play a note
    def play(self, fileName):
        try:
            self.notes[fileName].play()
        except:
            print(fileName + ' not found!')

    def playRandom(self):
        """play a random note"""
        index = random.randint(0, len(self.notes) - 1)
        note = list(self.notes.values())[index]
        note.play()


if __name__ == '__main__':
    # create note player
    nplayer = NotePlayer()

    # piano C4-E(b)-F-G-B(b)-C5
    pmNotes = {'C': 262, 'E': 311, 'F': 349, 'G': 391, 'B': 466}

    for name, freq in list(pmNotes.items()):
        nplayer.add(name + '.wav')

    fp = open("music.txt")
    wav = []
    rest = []
    while True:
        eof = fp.read(1)
        if eof == '':
            break
        wav.append(eof)
        eof = fp.read(1)
        if eof == '':
            break
        rest.append(int(eof))
    fp.close()

    for i in range(len(wav)):
        nplayer.play(wav[i] + '.wav')
        time.sleep(0.25 * rest[i])

第三问

  1. Add a --piano command line option to the project. When the project is run with this option, the user should be able to press the A, S, D, F, and G keys on a keyboard to play the five musical notes. (Hint: use pygame.event.get and pygame.event.type.)
import sys, os
import time, random
import wave, argparse, pygame
import numpy as np
from collections import deque
from matplotlib import pyplot as plt

# show plot of algorithm in action?
gShowPlot = False

# notes of a Pentatonic Minor scale
# piano C4-E(b)-F-G-B(b)-C5
pmNotes = {'C4': 262, 'Eb': 311, 'F': 349, 'G':391, 'Bb':466}

# write out WAVE file
def writeWAVE(fname, data):
    # open file
    file = wave.open(fname, 'wb')
    # WAV file parameters
    nChannels = 1
    sampleWidth = 2
    frameRate = 44100
    nFrames = 44100
    # set parameters
    file.setparams((nChannels, sampleWidth, frameRate, nFrames,
                    'NONE', 'noncompressed'))
    file.writeframes(data)
    file.close()

# generate note of given frequency
def generateNote(freq):
    nSamples = 44100
    sampleRate = 44100
    N = int(sampleRate/freq)
    # initialize ring buffer
    buf = deque([random.random() - 0.5 for i in range(N)])
    # plot of flag set
    if gShowPlot:
        axline, = plt.plot(buf)
    # init sample buffer
    samples = np.array([0]*nSamples, 'float32')
    for i in range(nSamples):
        samples[i] = buf[0]
        avg = 0.995*0.5*(buf[0] + buf[1])
        buf.append(avg)
        buf.popleft()
        # plot of flag set
        if gShowPlot:
            if i % 1000 == 0:
                axline.set_ydata(buf)
                plt.draw()

    # samples to 16-bit to string
    # max value is 32767 for 16-bit
    samples = np.array(samples * 32767, 'int16')
    return samples.tobytes()

# play a wav file
class NotePlayer:
    # constr
    def __init__(self):
        pygame.mixer.pre_init(44100, -16, 1, 2048)
        pygame.init()
        # dictionary of notes
        self.notes = {}
    # add a note
    def add(self, fileName):
        self.notes[fileName] = pygame.mixer.Sound(fileName)
    # play a note
    def play(self, fileName):
        try:
            self.notes[fileName].play()
        except:
            print(fileName + ' not found!')
    def playRandom(self):
        """play a random note"""
        index = random.randint(0, len(self.notes)-1)
        note = list(self.notes.values())[index]
        note.play()

# main() function
def main():
    # declare global var
    global gShowPlot

    parser = argparse.ArgumentParser(description="Generating sounds with Karplus String Algorithm.")
    # add arguments
    parser.add_argument('--display', action='store_true', required=False)
    parser.add_argument('--play', action='store_true', required=False)
    parser.add_argument('--piano', action='store_true', required=False)
    args = parser.parse_args()

    # show plot if flag set
    if args.display:
        gShowPlot = True
        plt.ion()

    # create note player
    nplayer = NotePlayer()

    print('creating notes...')
    for name, freq in list(pmNotes.items()):
        fileName = name + '.wav'
        if not os.path.exists(fileName) or args.display:
            data = generateNote(freq)
            print('creating ' + fileName + '...')
            writeWAVE(fileName, data)
        else:
            print('fileName already created. skipping...')

        # add note to player
        nplayer.add(name + '.wav')

        # play note if display flag set
        if args.display:
            nplayer.play(name + '.wav')
            time.sleep(0.5)

    # play a random tune
    if args.play:
        while True:
            try:
                nplayer.playRandom()
                # rest - 1 to 8 beats
                rest = np.random.choice([1, 2, 4, 8], 1,
                                        p=[0.15, 0.7, 0.1, 0.05])
                time.sleep(0.25*rest[0])
            except KeyboardInterrupt:
                exit()

    # random piano mode
    if args.piano:
        pygame.init()
        file = {'a': 'C4.wav', 's': 'Eb.wav', 'd': 'C4.wav', 'f': 'C4.wav', 'g': 'C4.wav'}

        size = width, height = 600, 400
        bg = (255, 255, 255)
        img = pygame.image.load("logo.jpg")
        position = img.get_rect()
        screen = pygame.display.set_mode(size)
        pygame.display.set_caption("piano")
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    cr = chr(event.key)
                    if cr in ['a', 's', 'd', 'f', 'g']:
                        nplayer.play(file[cr])

            pygame.display.flip()

if __name__ == '__main__':
    main()

第三问运行截图
在这里插入图片描述

Python极客项目编程 在本书中,你会看到14个令人兴奋的项目,旨在鼓励你探索Python编程的世界。这些项目涉及广泛的主题,如绘制类似万花尺的花纹、生成ASCII码艺术图、3D渲染,以及根据音乐同步投射激光图像。除了本身很有趣之外,这些项目的意图是提供一些起点,让你通过扩展每个项目,来探索你自己的想法。 立即下载

相关推荐

python极客项目编程pdf

python极客项目编程书籍,很好的一本深入学习python的书籍

Python极客项目编程 电子版

python编程进阶

Python极客项目编程.zip

Python极客项目编程

Python极客项目编程,手把手式教学,带你从小白进化成大神!

Python极客项目编程,手把手式教学,带你从小白进化成大神!

xiangxue888的博客 1517

从零开始学python必看,最强“Python编程三剑客(pdf)”

前三本书适合任何年龄的读者阅读,内容涵盖了编程的基础知识和项目实践,帮助初学者快速掌握Python编程。《Python编程快速上手-让繁琐工作自动化》还提供了一些实践项目和习题,帮助读者巩固所学的知识。

qq_41314882的博客 494

python极客项目编程 豆瓣,python极客项目编程目录

想学Python的你是不是一直被它生涩难懂的劝退?作为一个自学入门的程序员,依靠这样几本书和一套视频,两个月就学会了python。不卖关子,我学的就是”python编程三剑客“系列python六瓣花的画法。那么接下来就让我给你介绍介绍吧。(文末送福利)Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。(全套教程文末领取哈)

Fixf4556的博客 887

python极客项目编程怎么样,python极客项目编程目录

14.4.4用于LED的JavaScript处理程序267。6.3.5将ASCII文本图形字符串写入文本文件84。4.3.2实现Karplus-Strong算法55。13.3.1配置Arduino数字输出引脚238。第4章用Karplus-Strong算法产生。13.4.5将频率转换为电机速度和方向243。11.6.1定义颜色立方体的几何形状182。

2301_81896102的博客 775

python极客项目编程pdf微盘下载_Python极客项目编程

开发有趣的极客项目,掌握实用的Python编程技能Python 是一种解释型、面向对象、动态数据类型的高级程序设计语言。通过Python 编程,我们能够解决现实生活中的很多任务。Python极客项目编程pdf适合那些想要通过 Python 编程来进行尝试和探索的读者,适合了解基本的Python 语法和基本的编程概念的读者进一步学习。Python极客项目编程pdf图片预览图书特色Python是一种强...

weixin_42421177的博客 2613

python极客项目编程怎么样,python极客项目编程豆瓣

在生活中,我们需要用到许许多多的书籍来辅助我们,让知识变得更加的丰富,现在就让我们来看看有什么宝藏书籍吧号称当今最简单编程语言Python,自学绝对不是问题。不过任何事物都有个认识的过程,不可能没学过Python,直接就上手用Python干活的python自学行吗。所以这里还是要给你推荐一套从入门开始的教程:《Python编程三剑客:Python编程从入门到实践+快速上手+极客编程(共3册)(图灵+异步出品)》。

Aq1995的博客 881

赠书活动——《Python极客项目编程

最关键的是,读者会学会怎么把大问题拆成小问题,设计出解决问题的步骤,然后用Python一步步实现。本书适合已经了解了基本的Python语法和编程知识、想要尝试和探索通过Python编程解决实际问题的读者阅读,也可作为Python初学者练习项目开发的参考用书。直到今天,它依旧没被时间淘汰,也没让读者失望,美亚评分4.5,豆瓣评分9.8,畅销全球数十万册,便是最好的认证。这本书给初学者设计了一条清晰的学习路径,保姆式的讲解特别到位,能帮助读者快速学会用Python做出酷炫的应用。同时,此次更新重点关注。

m0_62283350的博客 929

【免费下载】 Python极客项目编程PDF资源下载

Python极客项目编程PDF资源下载 【下载地址】Python极客项目编程PDF资源下载 - **标题**: Python极客项目编程PDF- **描述**: Python极客项目编程书籍,很好的一本深入学习Python的书籍 ...

gitblog_09713的博客 1060

python极客项目编程百度云_Python极客项目编程pdf

下载地址:网盘下载内容简介······Python 是一种强大的编程语言,容易学习而且充满乐趣。但掌握了基本知识后,接下来做什么?本书包含了一组富有想象力的编程项目,它们将引导你用Python 来制作图像和音乐、模拟现实世界的现象,并与Arduino 和树莓派这样的硬件进行交互。你将学习使用常见的Python 工具和库,如numpy、matplotlib 和pygame,来完成以下工...

weixin_39899776的博客 1540
上一篇: C++计算器 支持复数运算
下一篇: 杨辉三角C++
todcode
博客等级 码龄7年 359粉丝 108原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值