Unityで録音アプリを作成
はじめに
Unityで録音アプリを作成してみました。
今回は録音して再生する機能を持ったアプリです。
目的
Unityで録音アプリを作成
環境
- Unity : 2018.1.6f1
- OS : Windows10
ソースコード
MITライセンス
UIのボタンを3つ作成して関数を関連付けしてください。
(StartButton, EndButton, PlayButton)
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MyRecording : MonoBehaviour { AudioClip myclip; AudioSource audioSource; string micName = "null"; //マイクデバイスの名前 const int samplingFrequency = 44100; //サンプリング周波数 const int maxTime_s = 300; //最大録音時間[s] void Start() { //マイクデバイスを探す foreach (string device in Microphone.devices) { Debug.Log("Name: " + device); micName = device; } } public void StartButton() { Debug.Log("recording start"); // deviceName: "null" -> デフォルトのマイクを指定 myclip = Microphone.Start(deviceName: micName, loop: false, lengthSec: maxTime_s, frequency: samplingFrequency); } public void EndButton() { if (Microphone.IsRecording(deviceName: micName) == true) { Debug.Log("recording stoped"); Microphone.End(deviceName: micName); } else { Debug.Log("not recording"); } } public void PlayButton() { Debug.Log("play"); audioSource = gameObject.GetComponent<AudioSource>(); audioSource.clip = myclip; audioSource.Play(); } }
コード解説
ソースコードを簡単に解説します。
まず、使用するマイクデバイスを探します。
ここでmicNameにnullを入れると、 その端末でデフォルトのマイクを使用します。
foreach (string device in Microphone.devices) { Debug.Log("Name: " + device); micName = device; }
Microphone.Startで録音を開始します。
引数は、マイクデバイスの名前、ループするかどうか、録音時間[s]、サンプリング周波数です。
Unity公式のリファレンスを読むと分かりやすいです。
録音データはAudioClip変数に保存されます。
myclip = Microphone.Start(deviceName: micName, loop: false, lengthSec: maxTime_s, frequency: samplingFrequency);
Microphone.Endで録音を停止します。
また、ループをfalseにしていると、録音時間を過ぎれば録音は終了します。
Microphone.End(deviceName: micName);
録音したデータを再生します。
audioSource.Play();
おわりに
Unityで録音機能を持ったアプリを作成しました。
あとは、録音データをセーブしたり、 音声ファイルとして書き出せたりすると、便利になりそうです。