LoginSignup
6
4

More than 3 years have passed since last update.

Unityエディタ拡張でサウンド再生を行う

Last updated at Posted at 2019-06-25

経緯

Unityのエディタ拡張でサウンドコンテナなどを作ってた時に保持したAudioClipの内容を再生したい( 該当AudioClipの場所にInspectorを移動したくない )場合に調べたのでここに共有

ちなみにデフォでサウンドファイル選択時に音声は鳴らせる→ここを参照

スクリプト

AudioClipの再生はここを参考に作成
停止方法が見つからなかったので探してきた

using System;
using UnityEngine;


#if UNITY_EDITOR
using System.Reflection;
using UnityEditor;
#endif


namespace Sample
{
    // SE,BGMの管理用コンテナクラス.
    [System.Serializable]
    public class SampleContainer : ScriptableObject
    {

        // 保持するデータ.
        [SerializeField] AudioClip soundData;


#if UNITY_EDITOR
        // SampleContainerのインスペクタ拡張.
        [CustomEditor(typeof(SampleContainer))]
        class SampleContainerEditor : UnityEditor.Editor
        {

            // インスペクタ描画.
            public override void OnInspectorGUI()
            {
                var data = target as SampleContainer;

                data.soundData = (AudioClip)EditorGUILayout.ObjectField("AudioClip", data.soundData, typeof(AudioClip));

                if (GUILayout.Button("PlayClip"))
                    this.PlayClip(data.soundData);

                if (GUILayout.Button("StopClip"))
                    this.StopClip(data.soundData);
            }


            // エディタ上でのサウンド再生.
            void PlayClip( 
                AudioClip clip)
            {
                if (clip == null) return;

                var unityEditorAssembly = typeof(AudioImporter).Assembly;
                var audioUtilClass = unityEditorAssembly.GetType("UnityEditor.AudioUtil");
                var method = audioUtilClass.GetMethod
                (
                    "PlayClip",
                    BindingFlags.Static | BindingFlags.Public,
                    null,
                    new Type[] {typeof(AudioClip)},
                    null
                );

                method.Invoke(null, new object[] {clip});
            }


            // エディタ上でのサウンドを停止する.
            void StopClip(
                AudioClip clip)
            {
                if (clip == null) return;

                var unityEditorAssembly = typeof(AudioImporter).Assembly;
                var audioUtilClass = unityEditorAssembly.GetType("UnityEditor.AudioUtil");
                var method = audioUtilClass.GetMethod(
                    "StopClip",
                    BindingFlags.Static | BindingFlags.Public,
                    null,
                    new Type[] {typeof(AudioClip)},
                    null
                );

                method.Invoke(null, new object[] {clip});
            }

        }
#endif
    }
}

実行画面

こんな感じ
image.png

ScriptableObjectをインスタンス化してAudioClipを設定して "Play" ボタンを押下すると再生 "Stop" を押下すると停止

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4