A coding page for kids. You learn the first things Python can do, one small step at a time: print, variables, strings, lists, loops, functions and if. Every step is a tiny program you can change and run right here, and some of them play music. Step by step, the programs build a whole song. In the last step your program sends the song to an AI that sings it, and you hear it. You need a computer or tablet with Chrome and sound, and your Hugging Face key for the last step. Nothing to install.一个给孩子们的编程页面。你会一小步一小步地学会 Python 最先能做的事:print、变量、字符串、列表、循环、函数和 if。每一步都是一个小程序,你可以就在这里修改和运行,有的还会弹奏音乐。一步一步地,这些程序拼成一整首歌。最后一步,你的程序把歌发给一个会唱歌的 AI,然后你就能听到。你需要一台有 Chrome、能发声的电脑或平板,最后一步还需要你的 Hugging Face 密钥。什么都不用安装。
佩帕的泥巴 · Peppa's Mud. A reggae song in Chinese about a real farm pig called Peppa.佩帕的泥巴。一首中文雷鬼歌,唱的是农场里一只真正的小猪,名叫佩帕。
Python put the words together, and an AI model called ACE-Step 1.5 made the music and the voice. No person sang it. At the end of this page, your own program sends a song like this one.Python 把歌词拼在一起,一个叫 ACE-Step 1.5 的 AI 模型做出了音乐和歌声。没有真人唱。到这一页的最后,你自己的程序也会发出一首这样的歌。
| 中文 | English |
|---|---|
| 有一只小猪叫佩帕 | There is a little pig called Peppa. |
| 住在山脚下的小农家 | She lives on a little farm at the foot of the hill. |
| 太阳一出来天就热啦 | When the sun comes out, it gets hot. |
| 她几乎不会流汗怎么办呀 | She can hardly sweat, so what can she do? |
| 泥巴泥巴 凉凉的泥巴 | Mud, mud, cool, cool mud. |
| 佩帕在泥里滚一滚啦 | Peppa rolls around in the mud. |
| 不怕太阳 不怕晒伤啦 | Not afraid of the sun, not afraid of sunburn. |
| 小猪的空调就是泥巴 | A little pig's air conditioner is mud. |
| 她的鼻子最灵啦 | Her nose is her sharpest sense. |
| 土里藏的宝贝她都挖 | She digs up every treasure hidden in the soil. |
| 猪妈妈一听就认得她 | Her mother knows her as soon as she hears her. |
| 每只小猪声音都不一样呀 | Every piglet's voice is different. |
| 佩帕聪明 会玩电脑呀 | Peppa is clever: she can play a computer game. |
| 鼻子推着杆 点中那个靶 | Pushing a stick with her nose, she hits the target. |
| 谁在看着她 她心里清楚啦 | She knows very well who is watching her. |
| 和好朋友一起 摇着小尾巴 | With her good friends, she wags her little tail. |
| 她不是电视里的卡通 | She is not the cartoon on TV. |
| 是一只真正的小猪呀 | She is a real little pig. |
What you will do. You run seven small Python programs, one after another. Each one teaches one new thing, and each one makes a bigger piece of the song. Along the way, four little tunes let you hear what loops, functions and if do, and after each step a quick check asks you to guess what a tiny program prints. Then you change the last program to make a song about your own animal, and the AI sings it.
What you learn. print, variables, strings and f-strings, lists, for loops, len, functions with def and return, and choosing with if, elif and else.
What you need. A computer or tablet with Chrome or another new browser, and an internet connection. For step 7 you also need your Hugging Face account and its key. The music AI runs on Hugging Face's computers, and each account has enough free time there for about one song a day. Or, for step 8, a Mac with an Apple chip and about 11 GB free: then the music AI runs on your own Mac, with no key.
你要做什么。你一个接一个地运行七个小小的 Python 程序。每一个教你一样新东西,每一个都做出更大的一块歌。一路上还有四段小曲子,让你听到循环、函数和 if 在做什么;每一步之后还有一个小测验,让你猜一个小程序会打印什么。然后你修改最后一个程序,做一首关于你自己的动物的歌,AI 就会把它唱出来。
你会学到什么。print、变量、字符串和 f-string、列表、for 循环、len、用 def 和 return 写函数,还有用 if、elif 和 else 做选择。
你需要什么。一台有 Chrome 或其他新浏览器的电脑或平板,还有网络。第 7 步还需要你的 Hugging Face 账号和它的密钥。音乐 AI 在 Hugging Face 的电脑上运行,每个账号在那里的免费时间大约够一天做一首歌。或者,第 8 步需要一台用苹果芯片、有大约 11 GB 空闲空间的 Mac:这样音乐 AI 就在你自己的 Mac 上运行,不需要密钥。
Each step has a box of Python code. Press ▶ Run and Python runs it, right in this page. What the program prints shows up in the dark box under it. Before you press Run, the dark box shows what it printed when we ran it.
You can type in the code box. Change a word, press Run again, and see what happens. If you break it, Python tells you which line it did not understand. That is normal: every programmer sees that many times a day. ↺ Start again puts the code back the way it was.
The first Run takes a few seconds, while Python loads into the page. The 🎵 boxes play music, so turn your sound on. In a 🧠 check, guess first: Python then shows you if you were right.
每一步都有一个 Python 代码框。按 ▶ Run,Python 就会在这一页里运行它。程序打印的内容会出现在下面的深色框里。在你按 Run 之前,深色框里是我们运行时它打印的内容。
你可以在代码框里打字。改一个词,再按 Run,看看会发生什么。如果改坏了,Python 会告诉你它看不懂哪一行。这很正常:每个程序员一天都会看到很多次。↺ Start again 会把代码变回原来的样子。
第一次按 Run 要等几秒钟,因为 Python 正在载入这一页。带 🎵 的框会弹奏音乐,记得打开声音。在 🧠 测验里,先猜一猜:然后 Python 会告诉你猜对了没有。
print(...) shows something on the screen. A variable is a name that holds a value: name = "佩帕" means "from now on, name holds 佩帕". Words in quotes are called strings. Lines that start with # are comments: notes for people, and Python skips them.
print(...) 把东西显示在屏幕上。变量是一个装着值的名字:name = "佩帕" 的意思是"从现在起,name 装着佩帕"。引号里的字叫字符串。以 # 开头的行是注释:写给人看的笔记,Python 会跳过它们。
# Step 1: print and variables.
# A variable is a name that holds a value.
# The words in quotes are strings: Python keeps them exactly as you typed them.
name = "佩帕" # Peppa, the pig in our song
animal = "小猪" # a little pig
print("Hello!")
print(name)
print(animal)
print(name, "is a", "pig")
What it printed:它打印的内容:
Hello!
佩帕
小猪
佩帕 is a pig
Try this
"佩帕" to your own name, and press Run.print(name, name, name). What does it print?" and press Run. Read what Python says, then press Start again.试一试
"佩帕" 改成你自己的名字,按 Run。print(name, name, name)。它会打印什么?",按 Run。看看 Python 说了什么,再按 Start again。Pick an answer. Then Python shows you what it really prints, and you can change the code and run it.选一个答案。然后 Python 会告诉你它真正打印什么,你也可以改代码再运行。
# Check 1: what will this print?
animal = "pig"
animal = "dog"
print(animal)
✅ Right!✅ 答对了!
Not this one. The green answer is what Python prints.不是这个。绿色的答案才是 Python 打印的内容。
A variable holds one value at a time. The second line puts "dog" in animal, and "pig" is gone.一个变量一次只装一个值。第二行把 "dog" 放进 animal,"pig" 就没有了。
What Python printed:Python 打印的内容:
dog
Python can make sounds, too. from tune import play borrows a function called play from tune.py, a file this page gives you. Give play a string of notes and it plays them: C D E F G A B, small letters c d e for higher notes, and - for a beat of quiet. A variable can hold notes, just like words. Turn your sound on and press Run.
Try this: change first to "C E G c", or make up a tune of your own.
Python 还能发出声音。from tune import play 从 tune.py 借来一个叫 play 的函数,这个文件是这一页给你的。给 play 一个音符字符串,它就会弹出来:C D E F G A B,小写的 c d e 是更高的音,- 是安静一拍。变量能装音符,就像装文字一样。打开声音,按 Run。
试一试:把 first 改成 "C E G c",或者自己编一段曲子。
# Tune 1: Python can play notes too.
# "from tune import play" borrows the play function from tune.py,
# a file this page gives you. Then play("...") plays the notes in the string.
from tune import play
first = "G A B G" # a variable can hold notes, too
play(first)
play(first)
play("B c d -") # small letters are higher; - is a beat of quiet
What it printed:它打印的内容:
♪ G A B G
♪ G A B G
♪ B c d -
An f-string puts variables inside a string. Write f before the quotes, and each variable's name in curly brackets: f"有一只{animal}叫{name}" becomes 有一只小猪叫佩帕, "there is a little pig called Peppa". You can also join strings with +. len(...) counts: for a string, it counts the characters.
f-string 把变量放进字符串里。在引号前面写 f,把每个变量的名字写在花括号里:f"有一只{animal}叫{name}" 就变成"有一只小猪叫佩帕"。你也可以用 + 把字符串连起来。len(...) 用来数数:对字符串来说,它数的是字符。
# Step 2: make a line of the song from your variables.
# An f-string puts a variable inside a string: write f before the quotes,
# and the variable's name in {curly brackets}.
name = "佩帕"
animal = "小猪"
home = "山脚下的小农家" # a little farm at the foot of the hill
line1 = f"有一只{animal}叫{name}" # There is a little pig called Peppa.
line2 = "住在" + home # She lives on a little farm ... ("住在" = lives at)
print(line1)
print(line2)
print(len(line1), "characters in line 1")
What it printed:它打印的内容:
有一只小猪叫佩帕
住在山脚下的小农家
8 characters in line 1
Try this
animal to "小狗" (a little dog) and name to a dog's name.line3 = f"My {animal} is called {name}", and print it.试一试
animal 改成 "小狗",把 name 改成一只小狗的名字。line3 = f"My {animal} is called {name}",然后把它打印出来。Pick an answer. Then Python shows you what it really prints, and you can change the code and run it.选一个答案。然后 Python 会告诉你它真正打印什么,你也可以改代码再运行。
# Check 2: what will this print?
name = "Mimi"
print(f"Hello {name}")
print("Hello {name}")
✅ Right!✅ 答对了!
Not this one. The green answer is what Python prints.不是这个。绿色的答案才是 Python 打印的内容。
Only a string with f in front fills in its curly brackets. Without the f, Python prints {name} just as it is written.只有前面带 f 的字符串才会把花括号填上。没有 f,Python 会照原样打印 {name}。
What Python printed:Python 打印的内容:
Hello Mimi
Hello {name}
A list holds many things in order, inside square brackets. Here it holds the four lines of the first verse. A for loop takes the things out one by one: for line in verse: means "for each line in the verse, do the indented lines below". The spaces at the start of print(line) matter: they show Python what to repeat.
列表按顺序装着很多东西,写在方括号里。这里它装着第一段主歌的四行歌词。for 循环把东西一个一个拿出来:for line in verse: 的意思是"对主歌里的每一行,做下面缩进的那几行"。print(line) 前面的空格很重要:它告诉 Python 要重复做什么。
# Step 3: a list holds many lines, and a for loop goes through them one by one.
# A list is written in [square brackets], with a comma after each item.
verse = [
"有一只小猪叫佩帕", # There is a little pig called Peppa.
"住在山脚下的小农家", # She lives on a little farm at the foot of the hill.
"太阳一出来天就热啦", # When the sun comes out, it gets hot.
"她几乎不会流汗怎么办呀", # She can hardly sweat: what can she do?
]
print("[verse]")
for line in verse:
print(line)
print("This verse has", len(verse), "lines.")
What it printed:它打印的内容:
[verse]
有一只小猪叫佩帕
住在山脚下的小农家
太阳一出来天就热啦
她几乎不会流汗怎么办呀
This verse has 4 lines.
Try this
print("~") under print(line), with the same spaces in front. What happens?试一试
print(line) 下面加一行 print("~"),前面的空格要一样多。会发生什么?Pick an answer. Then Python shows you what it really prints, and you can change the code and run it.选一个答案。然后 Python 会告诉你它真正打印什么,你也可以改代码再运行。
# Check 3: what will this print?
for word in ["la", "la"]:
print(word)
print("end")
✅ Right!✅ 答对了!
Not this one. The green answer is what Python prints.不是这个。绿色的答案才是 Python 打印的内容。
Only the indented line is inside the loop, so it runs once for each word. print("end") has no spaces in front: it runs once, after the loop.只有缩进的那一行在循环里面,所以每个词运行一次。print("end") 前面没有空格:它在循环结束后只运行一次。
What Python printed:Python 打印的内容:
la
la
end
A list can hold the phrases of a tune, and a for loop plays them one after another. You may know this tune: it is very old, and nobody owns it. In French it is "Frère Jacques", and in Chinese 两只老虎, "two tigers".
Try this: add a phrase of your own to the end of the list.
列表可以装着一首曲子的各个乐句,for 循环把它们一句接一句地弹出来。你可能听过这首曲子:它很古老,不属于任何人。法语叫 "Frère Jacques",中文叫《两只老虎》。
试一试:在列表最后加一句你自己的乐句。
# Tune 3: a list of phrases, and a for loop that plays them in order.
# This is "Frere Jacques", the same tune as "Two Tigers" (两只老虎).
from tune import play
melody = [
"G A B G",
"G A B G",
"B c d -",
"B c d -",
"d e d c B G",
"d e d c B G",
"G D G -",
"G D G -",
]
for phrase in melody:
play(phrase)
print("That was", len(melody), "phrases.")
What it printed:它打印的内容:
♪ G A B G
♪ G A B G
♪ B c d -
♪ B c d -
♪ d e d c B G
♪ d e d c B G
♪ G D G -
♪ G D G -
That was 8 phrases.
The chorus is the part a song sings again and again. A function is a recipe you write once and use many times. def chorus(name): starts the recipe, and return hands back what it made: a list of lines. chorus("佩帕") uses the recipe. Give it another name, and you get the same chorus with that name in it.
The chorus says 小猪的空调就是泥巴: "a little pig's air conditioner is mud". That is true. Pigs can hardly sweat, so they roll in mud to cool down.
副歌是一首歌一遍又一遍唱的部分。函数是一个你写一次、能用很多次的食谱。def chorus(name): 是食谱的开头,return 把做好的东西交回来:一个歌词列表。chorus("佩帕") 就是在用这个食谱。给它换一个名字,你就得到同样的副歌,里面换成那个名字。
副歌唱"小猪的空调就是泥巴"。这是真的:猪几乎不会出汗,所以它们在泥里打滚来降温。
# Step 4: a function is a recipe you write once and use again and again.
# def gives it a name. return hands back what it made.
# A song sings its chorus many times, so the chorus is a function.
def chorus(name):
return [
"[chorus]",
"泥巴泥巴 凉凉的泥巴", # Mud, mud, cool, cool mud.
f"{name}在泥里滚一滚啦", # Peppa rolls around in the mud.
"不怕太阳 不怕晒伤啦", # Not afraid of the sun or of sunburn.
"小猪的空调就是泥巴", # A little pig's air conditioner is mud.
]
for line in chorus("佩帕"):
print(line)
print()
for line in chorus("小花"): # the same recipe for a pig called Little Flower
print(line)
What it printed:它打印的内容:
[chorus]
泥巴泥巴 凉凉的泥巴
佩帕在泥里滚一滚啦
不怕太阳 不怕晒伤啦
小猪的空调就是泥巴
[chorus]
泥巴泥巴 凉凉的泥巴
小花在泥里滚一滚啦
不怕太阳 不怕晒伤啦
小猪的空调就是泥巴
Try this
试一试
Pick an answer. Then Python shows you what it really prints, and you can change the code and run it.选一个答案。然后 Python 会告诉你它真正打印什么,你也可以改代码再运行。
# Check 4: what will this print?
def double(x):
return x + x
print(double("ha"))
✅ Right!✅ 答对了!
Not this one. The green answer is what Python prints.不是这个。绿色的答案才是 Python 打印的内容。
double("ha") hands "ha" to the function as x, and it returns x + x. Adding two strings joins them.double("ha") 把 "ha" 作为 x 交给函数,函数返回 x + x。两个字符串相加,就是把它们连起来。
What Python printed:Python 打印的内容:
haha
In this tune every phrase comes twice. So we write a function, twice, that plays a phrase two times, and use it four times. Look at what it prints: the same lines as tune 3, from four short calls instead of an eight-line list. That is what functions are for.
Try this: write a function three_times, and use it.
这首曲子的每一句都出现两次。所以我们写一个函数 twice,把一句弹两遍,然后用它四次。看看它打印的内容:和第 3 段曲子一模一样,却只用了四次简短的调用,而不是八行的列表。这就是函数的用处。
试一试:写一个函数 three_times,然后用一用。
# Tune 4: in this song every phrase comes twice.
# So write a function that plays a phrase twice, and use it four times.
# Four short lines now do the work of the eight-line list in tune 3.
from tune import play
def twice(phrase):
play(phrase)
play(phrase)
twice("G A B G")
twice("B c d -")
twice("d e d c B G")
twice("G D G -")
What it printed:它打印的内容:
♪ G A B G
♪ G A B G
♪ B c d -
♪ B c d -
♪ d e d c B G
♪ d e d c B G
♪ G D G -
♪ G D G -
Lists can be added with +, like train cars joined into one long train. The song is verse, chorus, verse, chorus, verse, bridge, chorus. Then "\n".join(song) glues all the lines into one long string, with a new line between each one. That string is exactly what the AI will sing.
The words in square brackets, like [verse] and [chorus], are for the AI: they tell it which part of the song comes next. It doesn't sing them.
The whole song is 40 lines and 342 characters long.
列表可以用 + 加起来,就像火车车厢连成一列长长的火车。这首歌是:主歌、副歌、主歌、副歌、主歌、桥段、副歌。然后 "\n".join(song) 把所有的行粘成一个长长的字符串,每两行之间换一行。这个字符串就是 AI 要唱的内容。
方括号里的词,比如 [verse] 和 [chorus],是写给 AI 看的:它们告诉 AI 接下来是歌的哪一部分。AI 不会把它们唱出来。
整首歌一共 40 行,342 个字符。
# Step 5: put the whole song together.
# Lists can be added with +, like train cars joined into one train.
# "\n".join(...) glues the lines into one text, with a new line between them.
# Each part ends with "" so there is an empty line between parts.
name = "佩帕"
def chorus(name):
return [
"[chorus]",
"泥巴泥巴 凉凉的泥巴", # Mud, mud, cool, cool mud.
f"{name}在泥里滚一滚啦", # Peppa rolls around in the mud.
"不怕太阳 不怕晒伤啦", # Not afraid of the sun or of sunburn.
"小猪的空调就是泥巴", # A little pig's air conditioner is mud.
"",
]
verse1 = [
"[verse]",
f"有一只小猪叫{name}", # There is a little pig called Peppa.
"住在山脚下的小农家", # She lives on a little farm at the foot of the hill.
"太阳一出来天就热啦", # When the sun comes out, it gets hot.
"她几乎不会流汗怎么办呀", # She can hardly sweat: what can she do?
"",
]
verse2 = [
"[verse]",
"她的鼻子最灵啦", # Her nose is her sharpest sense.
"土里藏的宝贝她都挖", # She digs up every treasure hidden in the soil.
"猪妈妈一听就认得她", # Her mother knows her as soon as she hears her.
"每只小猪声音都不一样呀", # Every piglet's voice is different.
"",
]
verse3 = [
"[verse]",
f"{name}聪明 会玩电脑呀", # Peppa is clever: she can play a computer game.
"鼻子推着杆 点中那个靶", # Pushing a stick with her nose, she hits the target.
"谁在看着她 她心里清楚啦", # She knows very well who is watching her.
"和好朋友一起 摇着小尾巴", # With her good friends, she wags her little tail.
"",
]
bridge = [
"[bridge]",
"她不是电视里的卡通", # She is not the cartoon on TV.
"是一只真正的小猪呀", # She is a real little pig.
"",
]
song = verse1 + chorus(name) + verse2 + chorus(name) + verse3 + bridge + chorus(name)
lyrics = "\n".join(song)
print(lyrics)
print(len(song), "lines and", len(lyrics), "characters")
What it printed:它打印的内容:
[verse]
有一只小猪叫佩帕
住在山脚下的小农家
太阳一出来天就热啦
她几乎不会流汗怎么办呀
[chorus]
泥巴泥巴 凉凉的泥巴
佩帕在泥里滚一滚啦
不怕太阳 不怕晒伤啦
小猪的空调就是泥巴
[verse]
她的鼻子最灵啦
土里藏的宝贝她都挖
猪妈妈一听就认得她
每只小猪声音都不一样呀
[chorus]
泥巴泥巴 凉凉的泥巴
佩帕在泥里滚一滚啦
不怕太阳 不怕晒伤啦
小猪的空调就是泥巴
[verse]
佩帕聪明 会玩电脑呀
鼻子推着杆 点中那个靶
谁在看着她 她心里清楚啦
和好朋友一起 摇着小尾巴
[bridge]
她不是电视里的卡通
是一只真正的小猪呀
[chorus]
泥巴泥巴 凉凉的泥巴
佩帕在泥里滚一滚啦
不怕太阳 不怕晒伤啦
小猪的空调就是泥巴
40 lines and 342 characters
Try this
name = "佩帕" at the top. How many lines change? That is why we used a variable.试一试
name = "佩帕"。有几行跟着变了?这就是我们用变量的原因。Pick an answer. Then Python shows you what it really prints, and you can change the code and run it.选一个答案。然后 Python 会告诉你它真正打印什么,你也可以改代码再运行。
# Check 5: what will this print?
a = ["do", "re"]
b = ["mi"]
song = a + b
print(len(song))
print("-".join(song))
✅ Right!✅ 答对了!
Not this one. The green answer is what Python prints.不是这个。绿色的答案才是 Python 打印的内容。
a + b makes one list of three things. "-".join(song) puts a - between them.a + b 变成一个有三样东西的列表。"-".join(song) 在它们之间放上 -。
What Python printed:Python 打印的内容:
3
do-re-mi
The AI needs a style too: a few words that say what the music sounds like. if, elif and else let Python choose. language == "en" asks "is the language English?" (two = to ask, one = to give a variable its value). Only the first true choice runs.
Numbers have no quotes, so Python can do sums with them. bpm is beats per minute: a bigger number is a faster song. seconds // 60 divides and keeps the whole number.
AI 还需要一个风格:几个词,说明音乐听起来是什么样的。if、elif 和 else 让 Python 来选择。language == "en" 是在问"语言是英语吗?"(两个 = 是问,一个 = 是给变量一个值)。只有第一个成立的选择会运行。
数字不加引号,所以 Python 能用它们算数。bpm 是每分钟的拍数:数字越大,歌越快。seconds // 60 做除法,只留下整数。
# Step 6: choose how the song sounds.
# if, elif and else let Python choose. == asks "are these the same?"
# Numbers have no quotes: Python can do sums with them.
language = "zh" # "en" is English, "th" is Thai, "zh" is Chinese
if language == "en":
voice = "cheerful female vocal singing in English"
elif language == "th":
voice = "cheerful female vocal singing in Thai"
else:
voice = "cheerful female vocal singing in Mandarin Chinese"
music = ("reggae, one drop rhythm, offbeat skank guitar, organ bubble, "
"warm round bass, happy children's song")
style = music + ", " + voice
bpm = 80 # beats per minute: a bigger number is a faster song
seconds = 120 # how long the song is
print(style)
print(bpm, "beats a minute and", seconds, "seconds long")
print("That is", seconds // 60, "minutes.")
What it printed:它打印的内容:
reggae, one drop rhythm, offbeat skank guitar, organ bubble, warm round bass, happy children's song, cheerful female vocal singing in Mandarin Chinese
80 beats a minute and 120 seconds long
That is 2 minutes.
Try this
language to "th", then to "en". Which line of the if runs each time?"lively luk thung, phin, khaen" or "soft piano lullaby".试一试
language 改成 "th",再改成 "en"。每次是 if 的哪一行在运行?"lively luk thung, phin, khaen" 或 "soft piano lullaby"。Pick an answer. Then Python shows you what it really prints, and you can change the code and run it.选一个答案。然后 Python 会告诉你它真正打印什么,你也可以改代码再运行。
# Check 6: what will this print?
language = "th"
if language == "en":
print("English")
elif language == "zh":
print("Chinese")
else:
print("something else")
✅ Right!✅ 答对了!
Not this one. The green answer is what Python prints.不是这个。绿色的答案才是 Python 打印的内容。
language is "th": not "en" and not "zh". When no if or elif is true, else runs.language 是 "th":既不是 "en",也不是 "zh"。当 if 和 elif 都不成立时,就运行 else。
What Python printed:Python 打印的内容:
something else
Here if chooses a speed from a mood. In play(..., bpm=bpm) the first bpm is the name that play uses, and the second is our variable with the number in it.
Try this: set mood to "sleepy", then to "silly".
这里 if 根据心情选择速度。在 play(..., bpm=bpm) 里,第一个 bpm 是 play 用的名字,第二个是我们装着数字的变量。
试一试:把 mood 设成 "sleepy",再设成 "silly"。
# Tune 6: if chooses how fast the tune goes. bpm is beats per minute.
from tune import play
mood = "happy" # try "sleepy" or "silly"
if mood == "happy":
bpm = 140
elif mood == "sleepy":
bpm = 60
else:
bpm = 300
print("The", mood, "speed is", bpm, "beats a minute.")
play("G A B G G A B G", bpm=bpm)
play("B c d - B c d -", bpm=bpm)
What it printed:它打印的内容:
The happy speed is 140 beats a minute.
♪ G A B G G A B G
♪ B c d - B c d -
The music AI runs on Hugging Face's computers. Your key tells it that the song is yours, so it uses your free time there. A key is like a password:
No key yet? Log in at huggingface.co/settings/tokens, press Create new token, choose Read, give it a name such as "my songs", and press Create. Copy it: it starts with hf_. Ask a teacher if you get stuck.
音乐 AI 在 Hugging Face 的电脑上运行。你的密钥告诉它这首歌是你的,所以它用的是你在那里的免费时间。密钥就像密码一样:
还没有密钥?登录 huggingface.co/settings/tokens,按 Create new token,选 Read,起一个名字,比如"my songs",再按 Create。把它复制下来:它以 hf_ 开头。如果卡住了,就问问老师。
This is the whole song from steps 5 and 6 in one program, with one new line at the top: from song_machine import make_song. As in tune 1, import borrows a function from another file. This page gives you song_machine.py, and its make_song sends your words and your style to the music AI.
Press Run once. The song takes about two minutes, and then a player appears under the dark box. Each account can make about one song a day, so change the program until it is just right before you press Run.
这是第 5 步和第 6 步的整首歌,放在一个程序里,最上面多了一行新的:from song_machine import make_song。和第 1 段曲子一样,import 是从另一个文件借一个函数来用。这一页给你 song_machine.py,里面的 make_song 会把你的歌词和风格发给音乐 AI。
按一次 Run。做歌大约要两分钟,然后深色框下面会出现一个播放器。每个账号一天大约能做一首歌,所以先把程序改到你满意,再按 Run。
# Step 7: your whole song in one program, sent to the AI to sing.
# Change the words, the name, the language and the music to make it yours.
# make_song comes from song_machine.py, which this page gives you.
from song_machine import make_song
name = "佩帕"
language = "zh" # "en" is English, "th" is Thai, "zh" is Chinese
def chorus(name):
return [
"[chorus]",
"泥巴泥巴 凉凉的泥巴", # Mud, mud, cool, cool mud.
f"{name}在泥里滚一滚啦", # Peppa rolls around in the mud.
"不怕太阳 不怕晒伤啦", # Not afraid of the sun or of sunburn.
"小猪的空调就是泥巴", # A little pig's air conditioner is mud.
"",
]
verse1 = [
"[verse]",
f"有一只小猪叫{name}", # There is a little pig called Peppa.
"住在山脚下的小农家", # She lives on a little farm at the foot of the hill.
"太阳一出来天就热啦", # When the sun comes out, it gets hot.
"她几乎不会流汗怎么办呀", # She can hardly sweat: what can she do?
"",
]
verse2 = [
"[verse]",
"她的鼻子最灵啦", # Her nose is her sharpest sense.
"土里藏的宝贝她都挖", # She digs up every treasure hidden in the soil.
"猪妈妈一听就认得她", # Her mother knows her as soon as she hears her.
"每只小猪声音都不一样呀", # Every piglet's voice is different.
"",
]
verse3 = [
"[verse]",
f"{name}聪明 会玩电脑呀", # Peppa is clever: she can play a computer game.
"鼻子推着杆 点中那个靶", # Pushing a stick with her nose, she hits the target.
"谁在看着她 她心里清楚啦", # She knows very well who is watching her.
"和好朋友一起 摇着小尾巴", # With her good friends, she wags her little tail.
"",
]
bridge = [
"[bridge]",
"她不是电视里的卡通", # She is not the cartoon on TV.
"是一只真正的小猪呀", # She is a real little pig.
"",
]
song = verse1 + chorus(name) + verse2 + chorus(name) + verse3 + bridge + chorus(name)
lyrics = "\n".join(song)
if language == "en":
voice = "cheerful female vocal singing in English"
elif language == "th":
voice = "cheerful female vocal singing in Thai"
else:
voice = "cheerful female vocal singing in Mandarin Chinese"
music = ("reggae, one drop rhythm, offbeat skank guitar, organ bubble, "
"warm round bass, happy children's song")
style = music + ", " + voice
make_song(lyrics, style, bpm=80, seconds=120, language=language)
What your program prints:你的程序打印的内容:
"""song_machine.py: send a song to the free ACE-Step music model and play it.
The page loads this file into its Python for you, so step 7 can say
"from song_machine import make_song". You do not need to change it.
It talks to the model's page on Hugging Face (a "Space") the way that page's own
"make a song" button does. Your Hugging Face key goes with it, so the song
uses your own free GPU time: about one song a day.
"""
import asyncio
import json
import uuid
from js import document
from pyodide.http import pyfetch
SPACE = "https://ace-step-ace-step-v1-5.hf.space"
ENDPOINT = "generation_wrapper"
SEED = "88" # the same seed and the same words give the same song
SONGS = [] # songs still being made; Python keeps them here until they finish
def make_song(lyrics, style, bpm, seconds, language):
"""Send the song, and come back straight away. The song arrives later."""
key = document.getElementById("hf-key").value.strip()
if not key.startswith("hf_"):
print("First put your Hugging Face key in the key box. It starts with hf_")
return
print("Sending your song to the AI. It takes about two minutes...")
SONGS.append(asyncio.ensure_future(sing(key, lyrics, style, bpm, seconds, language)))
async def sing(key, lyrics, style, bpm, seconds, language):
try:
message = await ask_space(key, lyrics, style, bpm, seconds, language)
except Exception as error:
print("Something went wrong on the way:", error)
return
output = message["output"]
if not message.get("success"):
print("The AI did not make the song.")
print(output.get("title"), "-", output.get("error"))
if "quota" in str(output.get("title")).lower():
print("Your free song time for today is used up. Try again when that time has passed.")
return
show(output["data"][0]["url"])
print("Your song is ready! Press play.")
async def ask_space(key, lyrics, style, bpm, seconds, language):
"""Fill in the Space's form, join its queue, and wait for the answer."""
headers = {"Authorization": "Bearer " + key}
# 1. Ask the Space what its button needs, and the usual value of each input.
config = await (await pyfetch(SPACE + "/config", headers=headers)).json()
info = await (await pyfetch(SPACE + "/gradio_api/info", headers=headers)).json()
button = [d for d in config["dependencies"] if d.get("api_name") == ENDPOINT][0]
inputs = info["named_endpoints"]["/" + ENDPOINT]["parameters"]
values = {}
for item in inputs:
values[item["parameter_name"]] = item.get("parameter_default")
# 2. Put our song in place of the usual values.
values["selected_model"] = "acestep-v15-turbo"
values["generation_mode"] = "custom"
values["param_4"] = style
values["param_5"] = lyrics
values["param_6"] = bpm
values["param_9"] = language
values["param_12"] = False # don't pick a random seed: use ours
values["param_13"] = SEED
values["param_15"] = seconds
values["param_16"] = 1 # one song
values["param_47"] = "vocals"
# 3. The button's inputs in order. Some are hidden ("state"): they get None.
kinds = {}
for component in config["components"]:
kinds[component["id"]] = component["type"]
names = iter([item["parameter_name"] for item in inputs])
data = []
for component_id in button["inputs"]:
if kinds[component_id] == "state":
data.append(None)
else:
data.append(values[next(names)])
# 4. Join the queue, then read the Space's messages until the song is done.
session = uuid.uuid4().hex[:11]
request = {"data": data, "fn_index": button["id"], "trigger_id": None,
"session_hash": session, "event_data": None}
joined = await pyfetch(SPACE + "/gradio_api/queue/join", method="POST",
headers={**headers, "Content-Type": "application/json"},
body=json.dumps(request))
if not joined.ok:
raise RuntimeError(f"the Space said {joined.status}: is the key right?")
stream = await pyfetch(f"{SPACE}/gradio_api/queue/data?session_hash={session}",
headers=headers)
for line in (await stream.string()).splitlines():
if line.startswith("data:"):
message = json.loads(line[5:])
if message.get("msg") == "process_completed":
return message
raise RuntimeError("the Space stopped before the song was finished")
def show(url):
"""Put a player for the song on the page."""
place = document.getElementById("your-song")
player = document.createElement("audio")
player.controls = True
player.src = url
link = document.createElement("a")
link.href = url
link.textContent = "⬇ Open your song to save it"
place.replaceChildren(player, link)
The music model can also run on your own computer. Then you need no key, and there is no one-song-a-day limit. The program is step 7's program with a new ending: instead of make_song, it loads the model with the model's own Python library, acestep, and asks it for the song.
What you need. A Mac with an Apple chip (M1 or newer): Macs with Intel chips cannot run it. About 11 GB of free space: the model's files take 9.5 GB, and its Python libraries much less. The internet, the first time only.
Where Hugging Face cannot be reached, as in mainland China, ACE-Step downloads the model from ModelScope instead, by itself.
音乐模型也可以在你自己的电脑上运行。这样你就不需要密钥,也没有一天一首歌的限制。这个程序就是第 7 步的程序,只是换了一个结尾:它不用 make_song,而是用模型自己的 Python 库 acestep 载入模型,请它做出这首歌。
你需要什么。一台用苹果芯片(M1 或更新)的 Mac:用 Intel 芯片的 Mac 运行不了。大约 11 GB 的空闲空间:模型文件占 9.5 GB,它的 Python 库要少得多。只有第一次需要联网。
在连不上 Hugging Face 的地方,比如中国大陆,ACE-Step 会自己改从 ModelScope 下载模型。
ACE-Step-1.5-main.curl -LsSf https://astral.sh/uv/install.sh | sh. Then close Terminal and open it again.cd ~/Downloads/ACE-Step-1.5-mainuv run python sing_local.py. The first time, uv installs the libraries and the program downloads the model, so it takes a long while. Your song appears in the my_songs folder as a .wav file.uv cache clean removes the spare copies uv keeps. When you no longer need the model, drag the ACE-Step-1.5-main folder to the Trash: the model's files are inside it.ACE-Step-1.5-main 的文件夹。curl -LsSf https://astral.sh/uv/install.sh | sh。然后关掉终端,再重新打开。cd ~/Downloads/ACE-Step-1.5-mainuv run python sing_local.py。第一次运行时,uv 要安装库,程序要下载模型,所以要等很久。你的歌会出现在 my_songs 文件夹里,是一个 .wav 文件。uv cache clean 会删掉 uv 留着的备用副本。不再需要模型的时候,把 ACE-Step-1.5-main 文件夹拖到废纸篓:模型文件都在里面。# Step 8: the same song, made by the music model on your own computer.
# Run it in the ACE-Step-1.5 folder: uv run python sing_local.py
# The first run downloads the model, about 10 GB. After that it needs no internet.
from acestep.handler import AceStepHandler
from acestep.llm_inference import LLMHandler
from acestep.inference import GenerationParams, GenerationConfig, generate_music
name = "佩帕"
language = "zh" # "en" is English, "th" is Thai, "zh" is Chinese
def chorus(name):
return [
"[chorus]",
"泥巴泥巴 凉凉的泥巴", # Mud, mud, cool, cool mud.
f"{name}在泥里滚一滚啦", # Peppa rolls around in the mud.
"不怕太阳 不怕晒伤啦", # Not afraid of the sun or of sunburn.
"小猪的空调就是泥巴", # A little pig's air conditioner is mud.
"",
]
verse1 = [
"[verse]",
f"有一只小猪叫{name}", # There is a little pig called Peppa.
"住在山脚下的小农家", # She lives on a little farm at the foot of the hill.
"太阳一出来天就热啦", # When the sun comes out, it gets hot.
"她几乎不会流汗怎么办呀", # She can hardly sweat: what can she do?
"",
]
verse2 = [
"[verse]",
"她的鼻子最灵啦", # Her nose is her sharpest sense.
"土里藏的宝贝她都挖", # She digs up every treasure hidden in the soil.
"猪妈妈一听就认得她", # Her mother knows her as soon as she hears her.
"每只小猪声音都不一样呀", # Every piglet's voice is different.
"",
]
verse3 = [
"[verse]",
f"{name}聪明 会玩电脑呀", # Peppa is clever: she can play a computer game.
"鼻子推着杆 点中那个靶", # Pushing a stick with her nose, she hits the target.
"谁在看着她 她心里清楚啦", # She knows very well who is watching her.
"和好朋友一起 摇着小尾巴", # With her good friends, she wags her little tail.
"",
]
bridge = [
"[bridge]",
"她不是电视里的卡通", # She is not the cartoon on TV.
"是一只真正的小猪呀", # She is a real little pig.
"",
]
song = verse1 + chorus(name) + verse2 + chorus(name) + verse3 + bridge + chorus(name)
lyrics = "\n".join(song)
if language == "en":
voice = "cheerful female vocal singing in English"
elif language == "th":
voice = "cheerful female vocal singing in Thai"
else:
voice = "cheerful female vocal singing in Mandarin Chinese"
music = ("reggae, one drop rhythm, offbeat skank guitar, organ bubble, "
"warm round bass, happy children's song")
style = music + ", " + voice
music_model = AceStepHandler()
status, ready = music_model.initialize_service(project_root=".", config_path="acestep-v15-turbo")
print(status)
planner = LLMHandler() # a second model that plans the song; we leave it off to save memory
params = GenerationParams(caption=style, lyrics=lyrics, vocal_language=language,
bpm=80, duration=120, seed=88, inference_steps=8)
config = GenerationConfig(batch_size=1, use_random_seed=False, seeds=[88], audio_format="wav")
result = generate_music(music_model, planner, params, config, save_dir="my_songs")
if result.success:
print("Your song is ready:", result.audios[0]["path"])
else:
print("The model did not make the song:", result.error)
What it printed on our computer, a Linux computer with an NVIDIA graphics card (not a Mac), so yours will look a little different:它在我们电脑上打印的内容。我们用的是一台带 NVIDIA 显卡的 Linux 电脑(不是 Mac),所以你的会有一点不一样:
[OK] Model initialized successfully on cuda
Main model: ./checkpoints/acestep-v15-turbo
VAE: checkpoints/vae
Text encoder: ./checkpoints/Qwen3-Embedding-0.6B
Dtype: torch.bfloat16
Attention: sdpa
Compiled: False
Quantization: Disabled
Offload to CPU: False
Offload DiT to CPU: False
MLX DiT: Disabled
MLX VAE: Disabled
Your song is ready: my_songs/fe757b90-ace2-2460-e6e1-11191ad016cd.wav
The song it made:它做出的歌:
name in step 7.[verse], [chorus] and [bridge].chorus function: the line you most want people to sing along to."en", "th" or "zh", and write the words in that language.music, then press Run.No key, or no song time left today? Write a tune for your words with play, and sing them yourself.
The AI does not always sing every word clearly. If a word gets lost, try a shorter line or a simpler word next time.
name。[verse]、[chorus] 和 [bridge]。chorus 函数里:你最想让大家跟着唱的那一句。"en"、"th" 或 "zh",用那种语言写歌词。music 里,然后按 Run。没有密钥,或者今天的做歌时间用完了?用 play 给你的歌词配一段曲子,自己唱出来。
AI 不一定每个字都唱得很清楚。如果有的字听不出来,下次试试更短的句子或者更简单的词。
There is also a cartoon pig called Peppa on TV. That cartoon belongs to a company called Hasbro. This song is not about the cartoon, and this page is not from Hasbro. It uses none of the cartoon's characters, words, music or pictures. Our Peppa is a real farm pig, and every line about her is a true fact about pigs. Where each fact comes from is at the bottom of this page.
电视上也有一只卡通小猪,叫 Peppa Pig。那部动画片属于一家叫孩之宝(Hasbro)的公司。这首歌不是关于那部动画片的,这一页也不是孩之宝做的。它没有用那部动画片的任何角色、台词、音乐或图片。我们的佩帕是农场里一只真正的小猪,唱她的每一句都是关于猪的真实知识。每个知识从哪里来,写在这一页的最下面。