Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

使用麦克风录音

Godot支持Windows, macOS, Linux, Android和iOS的游戏内音频录制.

一定要查看Viewport演示! 可以下载演示档案中的Viewport文件夹, 或: https://github.com/godotengine/godot-demo-projects/tree/master/audio/mic_record.

你需要在项目设置中启用音频输入,否则只能获得空的音频文件。

根节点的结构

该演示由单一场景组成, 这个场景包括两个主要部分:GUI和音频.

我们将重点介绍音频部分. 在本演示中, 创建了一个名为 Record 的总线, 效果为 Record, 用于处理音频录制. 用一个名为 AudioStreamPlayerAudioStreamRecord 进行录音.

../../_images/record_bus.png ../../_images/record_stream_player.png
var effect
var recording


func _ready():
    # We get the index of the "Record" bus.
    var idx = AudioServer.get_bus_index("Record")
    # And use it to retrieve its first effect, which has been defined
    # as an "AudioEffectRecord" resource.
    effect = AudioServer.get_bus_effect(idx, 0)

音频录制由 AudioEffectRecord 资源处理, 它有三个方法: get_recording(), is_recording_active(), 以及 set_recording_active().

func _on_record_button_pressed():
    if effect.is_recording_active():
        recording = effect.get_recording()
        $PlayButton.disabled = false
        $SaveButton.disabled = false
        effect.set_recording_active(false)
        $RecordButton.text = "Record"
        $Status.text = ""
    else:
        $PlayButton.disabled = true
        $SaveButton.disabled = true
        effect.set_recording_active(true)
        $RecordButton.text = "Stop"
        $Status.text = "Recording..."

在演示开始时, 录音效果是未激活. 当用户按下 RecordButton 时, 用 set_recording_active(true) 启用该效果.

在下一次按下按钮时, 由于 effect.is_recording_active()true, 可以通过调用 effect.get_recording() 将录制的流存储到 recording 变量中.

func _on_play_button_pressed():
    print(recording)
    print(recording.format)
    print(recording.mix_rate)
    print(recording.stereo)
    var data = recording.get_data()
    print(data.size())
    $AudioStreamPlayer.stream = recording
    $AudioStreamPlayer.play()

要回放录音, 你可以将录音指定为 AudioStreamPlayer 的流, 并调用 play().

func _on_save_button_pressed():
    var save_path = $SaveButton/Filename.text
    recording.save_to_wav(save_path)
    $Status.text = "Saved WAV file to: %s\n(%s)" % [save_path, ProjectSettings.globalize_path(save_path)]

要保存录音, 你需要调用 save_to_wav(), 并提供文件的路径. 在本演示中, 路径由用户通过 LineEdit 输入框定义.