c# - 如何播放动态加载的声音

标签 c# unity3d audio

我正在尝试为我的团队的声音设计师制作一个工具,让他能够听到他在 Unity 中播放的声音文件。

  • 检查它是否可加载
  • 检查音量是否合适
  • 检查是否正确循环

等等...

我的问题是找出 Unity 如何管理加载文件夹中某处的音频文件。

我发现很多话题都在谈论它,但没有真正解决如何让 Unity 动态加载外部文件的方法。

最佳答案

如果你想从与 .exe/.app 相同的目录加载文件,你可以使用这个:

  • 使用 System.IO DirectoryInfo() 获取所有文件名
  • 使用WWW 类 流式传输/加载找到的文件

这里是代码:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class SoundPlayer : MonoBehaviour {

    string absolutePath = "./"; // relative path to where the app is running

    AudioSource src;
    List<AudioClip> clips = new List<AudioClip>();
    int soundIndex = 0;

    //compatible file extensions
    string[] fileTypes = {"ogg","wav"};

    FileInfo[] files;

    void Start () {
        //being able to test in unity
        if(Application.isEditor)    absolutePath = "Assets/";
        if(src == null) src = gameObject.AddComponent<AudioSource>();
        reloadSounds();
    }

    void reloadSounds() {
        DirectoryInfo info = new DirectoryInfo(absolutePath);
        files = info.GetFiles();

        //check if the file is valid and load it
        foreach(FileInfo f in files) {
            if(validFileType(f.FullName)) {
                //Debug.Log("Start loading "+f.FullName);
                StartCoroutine(loadFile(f.FullName));
            }
        }
    }

    bool validFileType(string filename) {
        foreach(string ext in fileTypes) {
            if(filename.IndexOf(ext) > -1) return true;
        }
        return false;
    }

    IEnumerator loadFile(string path) {
        WWW www = new WWW("file://"+path);

        AudioClip myAudioClip = www.audioClip;
        while (!myAudioClip.isReadyToPlay)
        yield return www;

        AudioClip clip = www.GetAudioClip(false);
        string[] parts = path.Split('\\');
        clip.name = parts[parts.Length - 1];
        clips.Add(clip);
    }
}

[编辑]

如果人们想改进文件管理,我推荐 this link

关于c# - 如何播放动态加载的声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15948046/

相关文章:

c# - 从 .net 程序读取 linux 中的文件?

c# - WCF ServiceHost.Close() 延迟

c# - 嵌套在 UpdatePanel 中时 FileUpload 不起作用? C#

c# - 如何将 Vector3 转换为四元数?

c# - 如何在 Unity android 项目中制作自定义 firebase 事件?

c# - 如何从代码动态填充ListPreference?

Swift 等同于 Unity3d 协程?

amazon-web-services - AWS lambda 音频特征提取(存储层数不足)

java - 以秒为单位存储准确的音频位置是否安全?

ios - 提取MPMoviePlayerViewController音频以在后台继续收听