Audio importieren
Übersicht
Der Prozess des Audioimports zur Laufzeit kann in mehrere Schritte unterteilt werden:
- Einen Runtime Audio Importer erstellen
- An die benötigten Delegaten binden (OnProgress und OnResult)
- Audio aus einer Datei oder einem Puffer importieren
- Die importierte Sound Wave abspielen, die vom OnResult-Delegaten erhalten wurde (weitere Informationen hier)
Stellen Sie sicher, dass sowohl Runtime Audio Importer- als auch Sound Wave-Instanzen nicht vorzeitig vom Garbage Collector erfasst werden, indem Sie eine starke Referenz auf sie halten. Dies kann erreicht werden, indem Sie sie separaten Variablen mit UPROPERTY(), TStrongObjectPtr oder einer anderen Methode zuweisen, die das Objekt vor der Zerstörung bewahrt.
Unterstützte Audioformate
Runtime Audio Importer unterstützt den Import der folgenden Audioformate:
| Format | Beschreibung |
|---|---|
| MP3 | MPEG-1/2/2.5 Audio Layer I/II/III |
| WAV | Waveform Audio File Format |
| FLAC | Free Lossless Audio Codec |
| OGG VORBIS | Ogg-Container mit Vorbis-Audio |
| OGG OPUS | Ogg-Container mit Opus-Audio |
| BINK | Bink Audio |
| RAW (PCM) | Unkomprimierte Pulse-Code-Modulation-Audiodaten (Int8, UInt8, Int16, UInt16, Int32, UInt32, Float32) |
Beim Audioimport können Sie das Format entweder explizit angeben oder die automatische Format-Erkennung basierend auf Dateierweiterung oder Inhalt verwenden.
Streaming Audio Imports
Für Streaming-Szenarien, bei denen Audiodaten inkrementell empfangen werden (z. B. von einem Server, in Echtzeit erfasst oder aus Netzwerk-Streams), sollten Sie Streaming Sound Waves in Betracht ziehen.
Diese Methode bietet eine kontinuierliche Möglichkeit, Audiodaten an denselben Puffer der Sound Wave anzuhängen, was sie für Live-Streams oder große Dateien, die in Blöcken verarbeitet werden, geeignet macht. Weitere Details finden Sie in der Streaming Sound Wave-Dokumentation.
Grundlegende Implementierungsschritte
1. Runtime Audio Importer erstellen
Zuerst müssen Sie ein Runtime Audio Importer-Objekt erstellen. Sie sollten sicherstellen, dass es vom Garbage Collector als starke Referenz behandelt wird.
- Blueprint
- C++

// UPROPERTY() is used here to prevent the object from being prematurely garbage collected
UPROPERTY()
class URuntimeAudioImporterLibrary* Importer;
Importer = URuntimeAudioImporterLibrary::CreateRuntimeAudioImporter();
2. Lier au délégué OnProgress
Pour suivre la progression de l'importation des données audio, vous pouvez lier au délégué OnProgress (Blueprints) / OnProgressNative (C++).
- Blueprint
- C++

// Assuming Importer is a UE reference to a URuntimeAudioImporterLibrary object
// AddWeakLambda is used just as an example. You can use any other method to bind the delegate, such as AddUObject, AddUFunction, etc.
Importer->OnProgressNative.AddWeakLambda(this, [](int32 Percentage)
{
UE_LOG(LogTemp, Log, TEXT("Import progress: %d"), Percentage);
});
Cela vous permettra de surveiller la progression et, par exemple, d'implémenter un écran de chargement.
3. Lier au délégué OnResult
Pour être notifié lorsque le processus d'importation des données audio est terminé et pour accéder à la référence de l'onde sonore résultante, vous devez lier le délégué OnResult (Blueprints) / OnResultNative (C++).
- Blueprint
- C++

// Assuming Importer is a UE reference to a URuntimeAudioImporterLibrary object
// AddWeakLambda is used just as an example. You can use any other method to bind the delegate, such as AddUObject, AddUFunction, etc.
Importer->OnResultNative.AddWeakLambda(this, [](URuntimeAudioImporterLibrary* Importer, UImportedSoundWave* ImportedSoundWave, ERuntimeImportStatus Status)
{
UE_LOG(LogTemp, Log, TEXT("Import result: %s"), *UEnum::GetValueAsString(Status));
});
Assurez-vous que l'onde sonore importée est traitée comme une référence forte par le ramasse-miettes pour éviter une collecte prématurée non désirée. Cela peut être fait en la plaçant comme une variable séparée dans les Blueprints.
4. Démarrer l'import audio
Démarrez le processus d'import audio en appelant la fonction appropriée, qui peut gérer à la fois les formats de données audio compressées et non compressées.
- Blueprint
- C++

// Assuming Importer is a UE reference to a URuntimeAudioImporterLibrary object
// Import audio from a file
Importer->ImportAudioFromFile(TEXT("C:/Folder/AudioFile.mp3"), ERuntimeAudioFormat::Auto);
// Import audio from a buffer
TArray<uint8> AudioData = ...; // Fill the array with your audio data
Importer->ImportAudioFromBuffer(MoveTemp(AudioData), ERuntimeAudioFormat::OggVorbis);
// Import audio from a RAW file
Importer->ImportAudioFromRAWFile(TEXT("C:/Folder/AudioFile.raw"), ERuntimeRAWAudioFormat::Int8, 44100, 2);
// Import audio from a RAW buffer
TArray<uint8> RAWBuffer = ...; // Fill the array with your PCM int 16-bit audio data
Importer->ImportAudioFromRAWBuffer(MoveTemp(RAWBuffer), ERuntimeRAWAudioFormat::Int16, 44100, 2);
Fonctions utilitaires
Recherche de fichiers audio
Vous pouvez parcourir un répertoire à la recherche de fichiers audio pris en charge :
- Blueprint
- C++

URuntimeAudioUtilities::ScanDirectoryForAudioFiles(TEXT("C:/Folder/"), true,
FOnScanDirectoryForAudioFilesResultNative::CreateWeakLambda(this, [this](bool bSucceeded, const TArray<FString>& AudioFilePaths)
{
// Handle the result
}));
Exemple Complet
Voici un exemple d'implémentation complet pour l'importation audio :
- Blueprint
- C++

Ceci est un exemple de code basique pour importer de l'audio depuis un fichier.
L'exemple utilise la fonction ImportAudioExample située dans la classe UImportAudioClassExample au sein du module EXAMPLEMODULE.
Pour exécuter l'exemple avec succès, assurez-vous d'ajouter le module RuntimeAudioImporter soit à PublicDependencyModuleNames, soit à PrivateDependencyModuleNames dans le fichier .Build.cs, ainsi qu'au fichier .uproject de votre projet.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Object.h"
#include "ImportAudioClassExample.generated.h"
UCLASS(BlueprintType)
class EXAMPLEMODULE_API UImportAudioClassExample : public UObject
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable)
void ImportAudioExample();
private:
// Please pay attention to making the RuntimeAudioImporter a hard reference, such as using UPROPERTY(), to prevent it from being prematurely garbage collected
UPROPERTY()
class URuntimeAudioImporterLibrary* RuntimeAudioImporter;
};
#include "ImportAudioClassExample.h"
#include "RuntimeAudioImporterLibrary.h"
void UImportAudioClassExample::ImportAudioExample()
{
RuntimeAudioImporter = URuntimeAudioImporterLibrary::CreateRuntimeAudioImporter();
if (!IsValid(RuntimeAudioImporter))
{
UE_LOG(LogTemp, Error, TEXT("Failed to create audio importer"));
return;
}
RuntimeAudioImporter->OnProgressNative.AddWeakLambda(this, [](int32 Percentage)
{
UE_LOG(LogTemp, Log, TEXT("Audio importing percentage: %d"), Percentage);
});
RuntimeAudioImporter->OnResultNative.AddWeakLambda(this, [this](URuntimeAudioImporterLibrary* Importer, UImportedSoundWave* ImportedSoundWave, ERuntimeImportStatus Status)
{
if (Status == ERuntimeImportStatus::SuccessfulImport)
{
UE_LOG(LogTemp, Warning, TEXT("Successfully imported audio with sound wave %s"), *ImportedSoundWave->GetName());
// Here you can handle ImportedSoundWave playback, like "UGameplayStatics::PlaySound2D(GetWorld(), ImportedSoundWave);"
}
else
{
UE_LOG(LogTemp, Error, TEXT("Failed to import audio"));
}
RuntimeAudioImporter = nullptr;
});
RuntimeAudioImporter->ImportAudioFromFile(TEXT("C:/Folder/Example.mp3"), ERuntimeAudioFormat::Auto);
}