Last active
September 11, 2020 13:42
-
-
Save baobao/4e5d1332e030828d141c492f93ea3c06 to your computer and use it in GitHub Desktop.
Unityで録音し、メモリ上に保持した録音サウンドを再生するサンプルコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using UnityEngine; | |
/// <summary> | |
/// Unityで録音し、メモリ上に保持した録音サウンドを再生するサンプルコード | |
/// OnGUIでデバッグボタンを表示しています | |
/// </summary> | |
public class UnityMicRecording : MonoBehaviour | |
{ | |
/// <summary> | |
/// 録音するAudioClip | |
/// </summary> | |
private AudioClip _recordedClip; | |
/// <summary> | |
/// 再生させるオーディオソース | |
/// </summary> | |
private AudioSource _audioSource; | |
/// <summary> | |
/// 録音機材名リスト | |
/// </summary> | |
private readonly List<string> _micNames = new List<string>(); | |
/// <summary> | |
/// 録音に使用している機材名 | |
/// </summary> | |
private string _recordingMicName; | |
void Start() | |
{ | |
_micNames.Clear(); | |
foreach (string device in Microphone.devices) | |
{ | |
Debug.Log("DeviceName: " + device); | |
_micNames.Add(device); | |
} | |
} | |
/// <summary> | |
/// 録音機材名を指定して録音開始 | |
/// </summary> | |
public void StartRecord(string micName) | |
{ | |
if (string.IsNullOrEmpty(_recordingMicName) == false || string.IsNullOrEmpty(micName)) | |
{ | |
return; | |
} | |
_recordingMicName = micName; | |
_recordedClip = Microphone.Start(micName, false, 10, 44100); | |
} | |
/// <summary> | |
/// 現在使用している機材の録音を停止 | |
/// </summary> | |
public void EndRecord() | |
{ | |
if (string.IsNullOrEmpty(_recordingMicName) == false && Microphone.IsRecording(_recordingMicName)) | |
{ | |
Microphone.End(_recordingMicName); | |
} | |
_recordingMicName = null; | |
} | |
/// <summary> | |
/// メモリ上に保持した録音したオーディオを再生 | |
/// </summary> | |
public void PlayRecordedAudioClip() | |
{ | |
_audioSource = gameObject.GetComponent<AudioSource>(); | |
if (_audioSource == null) | |
{ | |
_audioSource = gameObject.AddComponent<AudioSource>(); | |
} | |
_audioSource.clip = _recordedClip; | |
_audioSource.Play(); | |
} | |
void OnGUI() | |
{ | |
foreach (var micName in _micNames) | |
{ | |
if (GUILayout.Button($"StartRecord : {micName}")) | |
{ | |
StartRecord(micName); | |
} | |
} | |
if (GUILayout.Button("EndRecord")) | |
{ | |
EndRecord(); | |
} | |
if (GUILayout.Button("PlayRecordedAudioClip")) | |
{ | |
PlayRecordedAudioClip(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment