Micro:bit参考

Micro:bit参考 > Micropython API > Audio(音频)

Audio 音频

This module allows you play sounds with the micro:bit.
此模块允许你使用 micro:bit 播放声音。

By default sound output will be via the edge connector on pin 0 and the built-in speaker (V2). You can connect wired headphones or a speaker to pin 0 and GND on the edge connector to hear the sounds.
默认情况下,声音输出将通过引脚 0 上的边缘连接器和 内置扬声器 (V2)。您可以将有线耳机或扬声器连接到边缘连接器上的引脚 0 和 GND 以听到声音。

The audio module can be imported as import audio or accessed via the microbit module as microbit.audio.
音频模块可以作为 import audio 导入,也可以通过 microbit 模块作为 microbit.audio 访问。

There are three different kinds of audio sources that can be played using the audio.play() function:
有三种不同类型的音频源可以使用 audio.play() 函数:

  1. Built in sounds (V2), e.g. audio.play(Sound.HAPPY)
    内置声音 (V2),例如 audio.play(Sound.HAPPY)

  2. Sound Effects (V2), a way to create custom sounds by configuring its parameters:
    Sound Effects (V2),一种通过配置其参数来创建自定义声音的方法:

    my_effect = audio.SoundEffect(freq_start=400, freq_end=2500, duration=500)
    audio.play(my_effect)
  3. Audio Frames, an iterable (like a list or a generator) of Audio Frames, which are lists of 32 samples with values from 0 to 255:
    Audio Frames,音频帧的可迭代对象(如列表或生成器),它是 32 个样本的列表,值从 0 到 255:

    square_wave = audio.AudioFrame()
    for i in range(16):
        square_wave[i] = 0
        square_wave[i + 16] = 255
    audio.play([square_wave] * 64)


Functions  函数 

audio.play(sourcewait=Truepin=pin0return_pin=None)

Play the audio source to completion.
播放音频源直至完成。

Parameters  参数:
  • source –   来源 –

    There are three types of data that can be used as a source:
    有三种类型的数据可以用作源:

    • Sound: The microbit module contains a list of built-in sounds, e.g. audio.play(Sound.TWINKLE). A full list can be found in the Built in sounds section.
      声音 :microbit 模块包含一系列内置声音,例如 audio.play(Sound.TWINKLE)。 完整的列表可以在 内置声音 部分找到。

    • SoundEffect: A sound effect, or an iterable of sound effects, created via the audio.SoundEffect() class
      SoundEffect:通过音频创建的声音效果或声音效果的可迭代对象。SoundEffect() 类

    • AudioFrame: An iterable of AudioFrame instances as described in the AudioFrame Technical Details section
      AudioFrame:AudioFrame 实例的可迭代对象,如 AudioFrame 技术详细信息部分所述

  • wait – If wait is True, this function will block until the source is exhausted.
    wait – 如果 wait 为 True,则此函数将阻止,直到源耗尽。

  • pin – An optional argument to specify the output pin can be used to override the default of pin0. If we do not want any sound to play we can use pin=None.
    pin – 用于指定输出引脚的可选参数可用于覆盖 pin0 的默认值。如果我们不想播放任何声音,可以使用 pin=None。

  • return_pin – specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the V2 revision.
    return_pin – 指定用于连接到外部扬声器而不是接地的差分边缘连接器引脚。对于 V2 校订。

audio.is_playing()

返回:

True if audio is playing, otherwise returns False.
如果正在播放音频, 则为 True,否则返回 False。

audio.stop()

Stops all audio playback.
停止所有音频播放。


Built-in sounds V2
内置声音 V2

The built-in sounds can be called using audio.play(Sound.NAME).
内置的声音可以使用 audio.play(Sound.NAME) 调用。

  • Sound.GIGGLE

  • Sound.HAPPY

  • Sound.HELLO

  • Sound.MYSTERIOUS

  • Sound.SAD

  • Sound.SLIDE

  • Sound.SOARING

  • Sound.SPRING

  • Sound.TWINKLE

  • Sound.YAWN


Sounds Example  声音示例 

from microbit import *

while True:
    if button_a.is_pressed() and button_b.is_pressed():
        # When pressing both buttons only play via the edge connector
        audio.play(Sound.HELLO, pin=pin0)
    elif button_a.is_pressed():
        # On button A play a sound and when it's done show an image
        audio.play(Sound.HAPPY)
        display.show(Image.HAPPY)
    elif button_b.is_pressed():
        # On button B play a sound and show an image at the same time
        audio.play(Sound.TWINKLE, wait=False)
        display.show(Image.BUTTERFLY)

    sleep(500)
    display.clear()


Sound Effects V2
音效 V2

classaudio.SoundEffect(freq_start=500freq_end=2500duration=500vol_start=255vol_end=0waveform=WAVEFORM_SQUAREfx=FX_NONEshape=SHAPE_LOG)

An SoundEffect instance represents a sound effect, composed by a set of parameters configured via the constructor or attributes.
SoundEffect 实例表示音效,由通过构造函数或属性配置的一组参数组成。

All the parameters are optional, with default values as shown above, and they can all be modified via attributes of the same name. For example, we can first create an effect my_effect = SoundEffect(duration=1000), and then change its attributes my_effect.duration = 500.
所有参数都是可选的,默认值如上所示,并且它们都可以通过同名的属性进行修改。例如,我们可以先创建一个 effect my_effect = SoundEffect(duration=1000) ,然后更改其属性 my_effect.duration = 500。

Parameters  参数:
  • freq_start – Start frequency in Hertz (Hz), default: 500
    freq_start – 以赫兹 (Hz) 为单位的起始频率,默认值:500

  • freq_end – End frequency in Hertz (Hz), default: 2500
    freq_end – 以赫兹 (Hz) 为单位的结束频率,默认值:2500

  • duration – Duration of the sound (ms), default: 500
    duration – 声音的持续时间 (ms),默认值:500

  • vol_start – Start volume value, range 0-255, default: 255
    vol_start – 起始卷值,范围 0-255,默认值:255

  • vol_end – End volume value, range 0-255, default: 0
    vol_end – End volume 值,范围 0-255,默认值:0

  • waveform – Type of waveform shape, one of these values: WAVEFORM_SINE, WAVEFORM_SAWTOOTH, WAVEFORM_TRIANGLE, WAVEFORM_SQUARE, WAVEFORM_NOISE (randomly generated noise). Default: WAVEFORM_SQUARE
    waveform – 波形形状的类型,以下值之一: WAVEFORM_SINE、WAVEFORM_SAWTOOTH、WAVEFORM_TRIANGLE、 WAVEFORM_SQUARE、WAVEFORM_NOISE(随机生成的噪声)。默认值:WAVEFORM_SQUARE

  • fx – Effect to add on the sound, one of the following values: FX_TREMOLO, FX_VIBRATO, FX_WARBLE, or FX_NONE. Default: FX_NONE
    fx – 用于添加声音的效果,以下值之一: FX_TREMOLO、FX_VIBRATO、FX_WARBLE 或 FX_NONE。默认值:FX_NONE

  • shape – The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: SHAPE_LINEAR, SHAPE_CURVE, SHAPE_LOG. Default: SHAPE_LOG
    shape – 开始频率和结束频率之间的插值曲线的类型,不同的波形具有不同的频率变化率。以下值之一:SHAPE_LINEAR、 SHAPE_CURVE,SHAPE_LOG。 默认值:SHAPE_LOG

copy()
Returns  返回:

A copy of the SoundEffect.
SoundEffect 的副本。

freq_start

Start frequency in Hertz (Hz), a number between 0 and 9999.
以赫兹 (Hz) 为单位的起始频率,一个介于 0 和 9999 之间的数字。

freq_end

End frequency in Hertz (Hz), a number between 0 and 9999`.
以赫兹 (Hz) 为单位的结束频率,一个介于 0 和 9999' 之间的数字。

duration

Duration of the sound in milliseconds, a number between 0 and 9999.
声音的持续时间(以毫秒为单位),介于 0 和 之间的数字 9999.

vol_start

Start volume value, a number between 0 and 255.
Start volume 值,介于 0 和 255 之间的数字。

vol_end

End volume value, a number between 0 and 255.
End volume 值,介于 0 和 255 之间的数字。

waveform

Type of waveform shape, one of these values: WAVEFORM_SINE, WAVEFORM_SAWTOOTH, WAVEFORM_TRIANGLE, WAVEFORM_SQUARE, WAVEFORM_NOISE (randomly generated noise).
波形形状类型,以下值之一:WAVEFORM_SINE、 WAVEFORM_SAWTOOTH、WAVEFORM_TRIANGLE、WAVEFORM_SQUARE、 WAVEFORM_NOISE(随机生成的噪声)。

fx

Effect to add on the sound, one of the following values: FX_TREMOLO, FX_VIBRATO, FX_WARBLE, or None.
Effect 以添加到声音上,以下值之一: FX_TREMOLO、FX_VIBRATO、FX_WARBLE 或 None。

shape

The type of interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: SHAPE_LINEAR, SHAPE_CURVE, SHAPE_LOG.
起始频率和结束频率之间的插值曲线类型,不同的波形具有不同的频率变化率。以下值之一:SHAPE_LINEAR、 SHAPE_CURVE,SHAPE_LOG。

The arguments used to create any Sound Effect, can be inspected by looking at each of the SoundEffect instance attributes, or by converting the instance into a string (which can be done via str() function, or by using a function that does the conversion automatically like print()).
用于创建任何 Sound Effect 的参数可以通过查看每个 SoundEffect 实例属性来检查,也可以通过将实例转换为字符串(可以通过 str() 完成)来检查。 函数,或者使用自动进行转换的函数,如 print()

For example, with the REPL you can inspect the default SoundEffects:
例如,使用 REPL,您可以检查默认的 SoundEffects:

>>> print(audio.SoundEffect()) 
SoundEffect(freq_start=500, freq_end=2500, duration=500, vol_start=255, vol_end=0, waveform=WAVE_SQUARE, fx=FX_NONE, shape=SHAPE_LOG) 

This format is “human readable”, which means it is easy for us to read, and it looks very similar to the code needed to create that SoundEffect, but it’s not quite right. The repr() function can be used to create a string of Python code that can be stored or transferred (you could transmit sounds via micro:bit radio!) and be executed with the eval() function:
这种格式是 “人类可读的”,这意味着它很容易阅读,并且它看起来与创建 SoundEffect 所需的代码非常相似,但并不完全正确。repr() 函数可用于创建 可以存储或传输的 Python 代码字符串 (你可以通过 micro:bit 收音机传输声音!并使用 eval() 函数:

>>> from audio import SoundEffect
>>> sound_code = repr(SoundEffect())
>>> print(sound_code)
SoundEffect(500, 2500, 500, 255, 0, 3, 0, 18)
>>> eval("audio.play({})".format(sound_code))


Sound Effects Example
音效示例 

from microbit import *

# Play the default Sound Effect
audio.play(audio.SoundEffect())

# Create a new Sound Effect and immediately play it
audio.play(audio.SoundEffect(
    freq_start=400,
    freq_end=2000,
    duration=500,
    vol_start=100,
    vol_end=255,
    waveform=audio.SoundEffect.WAVEFORM_TRIANGLE,
    fx=audio.SoundEffect.FX_VIBRATO,
    shape=audio.SoundEffect.SHAPE_LOG
))

# Play a Sound Effect instance, modify an attribute, and play it again
my_effect = audio.SoundEffect(
    freq_start=400,
    freq_end=2000,
)
audio.play(my_effect)
my_effect.duration = 1000
audio.play(my_effect)

# You can also create a new effect based on an existing one, and modify
# any of its characteristics via arguments
my_modified_effect = my_effect.copy()
my_modified_effect.waveform = audio.SoundEffect.WAVEFORM_NOISE
audio.play(my_modified_effect)

# Use sensor data to modify and play an existing Sound Effect instance
my_effect.duration = 600
while True:
    # int() might be temporarily needed: https://github.com/microbit-foundation/micropython-microbit-v2/issues/121
    my_effect.freq_start = int(scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 9999)))
    my_effect.freq_end = int(scale(accelerometer.get_y(), from_=(-2000, 2000), to=(0, 9999)))
    audio.play(my_effect)

    if button_a.is_pressed():
        # Button A silences the micro:bit
        speaker.off()
        display.show(Image("09090:00000:00900:09990:00900"))
        sleep(500)
    elif button_b.is_pressed():
        # Button B re-enables the speaker & plays an effect while showing an image
        speaker.on()
        audio.play(audio.SoundEffect(), wait=False)
        display.show(Image.MUSIC_QUAVER)
        sleep(500)

    sleep(150)


AudioFrame  音频帧 

classaudio.AudioFrame

An AudioFrame object is a list of 32 samples each of which is an unsigned byte (whole number between 0 and 255).
一个 AudioFrame 对象是一个包含 32 个样本的列表,每个样本都是一个无符号字节(介于 0 和 255 之间的整数)。

It takes just over 4 ms to play a single frame.
播放一帧只需 4 毫秒多一点。

copyfrom(other)

Overwrite the data in this AudioFrame with the data from another AudioFrame instance.
用另一个 AudioFrame 中的数据覆盖此 AudioFrame 中的数据 AudioFrame 实例。

Parameters  参数:

other – AudioFrame instance from which to copy the data.
other – 要从中复制数据的 AudioFrame 实例。


Technical Details
技术细节 

Note  注意

You don’t need to understand this section to use the audio module. It is just here in case you wanted to know how it works.
您无需了解此部分即可使用 audio 模块。它就在这里,以防您想知道它是如何工作的。

The audio module can consumes an iterable (sequence, like list or tuple, or generator) of AudioFrame instances, each 32 samples at 7812.5 Hz, and uses linear interpolation to output a PWM signal at 32.5 kHz, which gives tolerable sound quality.
音频模块可以使用可迭代的 AudioFrame 实例(序列,如列表、元组或生成器),每个实例 32 个样本,频率为 7812.5 Hz,并使用线性插值输出 32.5 kHz 的 PWM 信号,从而提供可容忍的音质。

The function play fully copies all data from each AudioFrame before it calls next() for the next frame, so a sound source can use the same AudioFrame repeatedly.
函数 play 在为下一帧调用 next() 之前会完全复制每个 AudioFrame 中的所有数据,因此声源可以使用相同的 AudioFrame 的 Alpha S T

The audio module has an internal 64 sample buffer from which it reads samples. When reading reaches the start or the mid-point of the buffer, it triggers a callback to fetch the next AudioFrame which is then copied into the buffer. This means that a sound source has under 4ms to compute the next AudioFrame, and for reliable operation needs to take less 2ms (which is 32000 cycles in micro:bit V1 or 128000 in V2, so should be plenty).
音频模块有一个内部的 64 个采样缓冲区,它可以从中读取采样。当读取到达缓冲区的起点或中点时,它会触发一个回调来获取下一个 AudioFrame,然后将其复制到 缓冲区。这意味着声源有不到 4 毫秒的时间来计算下一个 AudioFrame 的调用,并且为了可靠运行,需要花费更少的 2 毫秒(在 micro:bit V1 中是 32000 个周期,在 V2 中是 128000 个周期,所以应该足够了)。


AudioFrame Example
AudioFrame 示例 

from microbit import display, sleep, button_a
import audio
import math

def repeated_frame(frame, count):
    for i in range(count):
        yield frame

# Press button A to skip to next wave.
def show_wave(name, frame, duration=1500):
    display.scroll(name + " wave", wait=False,delay=100)
    audio.play(repeated_frame(frame, duration),wait=False)
    for i in range(75):
        sleep(100)
        if button_a.is_pressed():
            display.clear()
            audio.stop()
            break

frame = audio.AudioFrame()

for i in range(len(frame)):
    frame[i] = int(math.sin(math.pi*i/16)*124+128.5)
show_wave("Sine", frame)

triangle = audio.AudioFrame()

QUARTER = len(triangle)//4
for i in range(QUARTER):
    triangle[i] = i*15
    triangle[i+QUARTER] = 248-i*15
    triangle[i+QUARTER*2] = 128-i*15
    triangle[i+QUARTER*3] = i*15+8
show_wave("Triangle", triangle)

square = audio.AudioFrame()

HALF = len(square)//2
for i in range(HALF):
    square[i] = 8
    square[i+HALF] = 248
show_wave("Square", square)
sleep(1000)

for i in range(len(frame)):
    frame[i] = 252-i*8
show_wave("Sawtooth", frame)

del frame

#Generate a waveform that goes from triangle to square wave, reasonably smoothly.
frames = [ None ] * 32
for i in range(32):
    frames[i] = frame = audio.AudioFrame()
    for j in range(len(triangle)):
        frame[j] = (triangle[j]*(32-i) + square[j]*i)>>5

def repeated_frames(frames, count):
    for frame in frames:
        for i in range(count):
            yield frame

display.scroll("Ascending wave", wait=False)
audio.play(repeated_frames(frames, 60))