使用麦克风录音

Godot supports in-game audio recording for Windows, macOS, Linux, Android and iOS.

一定要查看Viewport演示! 可以下载演示档案中的Viewport文件夹,或https://github.com/godotengine/godot-demo-projects/tree/master/[viewport\_](#id1)。

根节点的结构

The demo consists of a single scene. This scene includes two major parts: the GUI and the audio.

We will focus on the audio part. In this demo, a bus named Record with the effect Record is created to handle the audio recording. An AudioStreamPlayer named AudioStreamRecord is used for recording.

../../_images/record_bus.png ../../_images/record_stream_player.png

GDScript

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

The audio recording is handled by the AudioEffectRecord resource which has three methods: get_recording(), is_recording_active(), and set_recording_active().

GDScript

  1. func _on_RecordButton_pressed():
  2. if effect.is_recording_active():
  3. recording = effect.get_recording()
  4. $PlayButton.disabled = false
  5. $SaveButton.disabled = false
  6. effect.set_recording_active(false)
  7. $RecordButton.text = "Record"
  8. $Status.text = ""
  9. else:
  10. $PlayButton.disabled = true
  11. $SaveButton.disabled = true
  12. effect.set_recording_active(true)
  13. $RecordButton.text = "Stop"
  14. $Status.text = "Recording..."

At the start of the demo, the recording effect is not active. When the user presses the RecordButton, the effect is enabled with set_recording_active(true).

On the next button press, as effect.is_recording_active() is true, the recorded stream can be stored into the recording variable by calling effect.get_recording().

GDScript

  1. func _on_PlayButton_pressed():
  2. print(recording)
  3. print(recording.format)
  4. print(recording.mix_rate)
  5. print(recording.stereo)
  6. var data = recording.get_data()
  7. print(data)
  8. print(data.size())
  9. $AudioStreamPlayer.stream = recording
  10. $AudioStreamPlayer.play()

To playback the recording, you assign the recording as the stream of the AudioStreamPlayer and call play().

GDScript

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

To save the recording, you call save_to_wav() with the path to a file. In this demo, the path is defined by the user via a LineEdit input box.