카테고리 없음

Unity에서 실행 중에 mp3 파일을 읽고 play하기

Wood Pecker 2021. 1. 28. 23:30

Unity에서 실행 중에 mp3 파일을 읽고 play하는 기능을 구현하여 보자. 먼제 GameObject에 AudioSource 컴포넌트를 붙여준다. 물론 Assets 폴더 하단에 Resources라는 폴더를 만들고 이곳에 mp3파일을 복사하여 넣어준다. 예를 들어 myfile.mp3라고 가정해보자. 다음은 핵심 코드이다.

오디오파일:

    AudioClip audio = Resources.Load("myfile",typeof(AudioClip))asAudioClip;

Resources.Load() 함수를 이용하며 파일의 확장명 즉 .mp3 를 붙이지 않는다. 경로명이 깊어지면 백슬레시가 아닌 forward slashe를 사용한다.

텍스트파일:

    TextAsset  myTxt = (TextAsset)Resources.Load("textfile", typeof(TextAsset));

    string myTextStr= myTxt.text;

이미지파일:

    Texture2D imgTexture = Resources.Load("texture\_file", typeof(Texture2D)) as Texture2D;

다음의 스크립트를 이용하여 테스트 하여보자.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[RequireComponent(typeof(AudioSource))]
public class MyPlayMp3 : MonoBehaviour
{
  private AudioSource audioSource;
  void Start()
  {
    audioSource = this.GetComponent<AudioSource>();

    AudioClip audioAsset = (AudioClip)Resources.Load("myfile");//myfile.mp3
    audioSource.clip = (AudioClip)audioAsset;
    audioSource.Play();
  }

  // Update is called once per frame
  void Update()
  {

  }
}

 

마이크를 이용하여 녹음하고 play하기

 

다음은 인터넷에서 찾은 코드이다. 마이크를 이용하여 녹음을 하고 플레이를 하는 방법이다. 요긴하게 사용할 수 있는 코드로 생각되어 여기에 정리해 놓는다.

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

[RequireComponent(typeof(AudioSource))]
public class MyRecoirdAndSpeak : MonoBehaviour  
{  
    private bool isMicConnected = false;  
    private int minFreq;  
    private int maxFreq;  
    private AudioSource audioSource;

    void Start()  
    {  
         if (Microphone.devices.Length <= 0)  
         {  
             Debug.LogWarning("마이크가 없습니다.");  
          }  
          else  
         {  
            isMicConnected = true;  
            Microphone.GetDeviceCaps(null, out minFreq, out maxFreq);  
            if (minFreq == 0 && maxFreq == 0)  
            {  
                 maxFreq = 44100; // 44100 Hz sampling frequency  
            }  
          }  
          audioSource = this.GetComponent();  
      }

       void Update()  
       {

       }

       void OnGUI()  
      {  
         if (isMicConnected)  
          {  
              if (!Microphone.IsRecording(null))  
              {  
                  if (GUI.Button(new Rect(100,100, 200, 50), "녹음하기"))  
                  {  
                       audioSource.clip = Microphone.Start(null, true, 20, maxFreq);  
                   }  
               }  
               else  
               {  
                    if (GUI.Button(new Rect(100, 100, 200, 50), "정지하고 플레이하기"))  
                    {  
                        Microphone.End(null);  
                        audioSource.Play();  
                     }  
                     GUI.Label(new Rect(100, 130, 200, 50), "녹음중...");  
                 }  
             }  
             else  
             {  
                  GUI.contentColor = Color.red;  
                  GUI.Label(new Rect(100, 100, 200, 50), "마이크가 없습니다.");  
              }  
           }  
 }  
반응형