0

我使用此代码打开我的设备资源管理器,选择一个音频文件并将其作为场景中对象的音频源剪辑插入。

    public GameObject evento;
    public AudioSource audio;
    string path = Application.streamingAssetsPath;

    EditorGUIController editorGUIController;


    private void Awake() {
        editorGUIController = GameObject.FindObjectOfType<EditorGUIController>();
        audio = evento.GetComponent<AudioSource>();            

    }

    public void InsertAudio(){ 
        #if UNITY_EDITOR
        
        path = EditorUtility.OpenFilePanel("Overwrite with wav", "", "wav");
        audio.clip = LoadMP3(path);
        
        #endif
    }

    public static AudioClip LoadMP3(string path){
        byte[] fileData;
        AudioClip clip = null;
        if (File.Exists(path)){
            int indice = path.LastIndexOf("/");
            string audioNameA = path.Substring(indice+1);
            string audioName = audioNameA.Substring(0, audioNameA.Length-4);


            fileData = File.ReadAllBytes(path);
            if(fileData.Length>0) {Debug.Log ("fileData: "+ fileData.ToString());}
            float[] samples = new float [fileData.Length/4 +1];

            Buffer.BlockCopy(fileData,0,samples,0,fileData.Length);
            int channels = 1;
            int sampleRate = 48000;
            clip = AudioClip.Create(audioName,samples.Length, channels,sampleRate,false);
            clip.SetData(samples,0);
        }
        return clip;
            
    }

不幸的是,当我启动此方法时,音频以非常烦人的噪音开始(可以说是电视的嗡嗡声):

   public void playAudio(){
           evento.GetComponent<AudioSource>().Play();
       }

我很确定问题出在浮点到音频源的转换中,但我不知道如何解决它。一些想法?

4

0 回答 0