NAudio 사용하기

using System;
using NAudio.Wave;

Guid deviceGUID = Guid.Empty;
DirectSoundOut directSoundOut = new DirectSoundOut(deviceGUID); 
//guid를 이용하여 direct sound out을 생성하면 해당 디바이스 출력을 선택할수 있음

Capabilitues 받아오기

WaveOut.DeviceCount; //디바이스 갯수
WaveOut.GetCapabilities(디바이스인덱스번호).ProductName.ToString(); //디바이스 이름

재생 샘플

using System;
using NAudio.Wave;

static string path_;
Mp3FileReader reader;
WaveOut waveOut = new WaveOut();
private void Start()
{
    path_ =  Application.dataPath + "/StreamingAssets/" + "sample_script_kr_1.mp3";
    reader = new Mp3FileReader(path_);
    //WaveOutCapabilities woc = WaveOut.GetCapabilities(0);
    waveOut.DeviceNumber = 1;
    waveOut.Init(reader);
    waveOut.Play();
}

private void OnApplicationQuit()
{
    waveOut.Stop();
    waveOut.Dispose();
}
  • 전체 파일스트림을 모두 dispose 해주지 않으면 메모리누수로 크래시가 나는것 같음
  • 하단의 샘플코드가 전체 파일스트림을 모두 dispose해서 에러가 없는 상태

크래시 에러 나지 않는 샘플코드

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using NAudio;
using NAudio.Wave;
using System.IO; // for FileStream

public class UnitySoundPlayer : MonoBehaviour
{
    static string file_path;
    FileStream file_stream;
    Mp3FileReader file_reader;
    WaveStream wave_stream;
    BlockAlignReductionStream block_align_reduction_stream;
    WaveOut wave_out;
    
    
    
    private void Start()
    {
        SoundPlay(0);
    }

    private void SoundPlay(int index)
    {
        file_path = Application.dataPath + "/StreamingAssets/" + "sample_script_kr_1.mp3";
        file_stream = File.OpenRead(file_path);
        file_reader = new Mp3FileReader(file_stream);
        wave_stream = WaveFormatConversionStream.CreatePcmStream(file_reader);
        block_align_reduction_stream = new BlockAlignReductionStream(wave_stream);
        wave_out = new WaveOut();
        //WaveOutCapabilities woc = WaveOut.GetCapabilities(0);
        wave_out.DeviceNumber = index;
        wave_out.Init(block_align_reduction_stream);
        wave_out.Play();
    }

    private void SoundDistroy()
    {
        wave_out.Stop();
        wave_out.Dispose();
        block_align_reduction_stream.Dispose();
        wave_stream.Dispose();
        file_reader.Dispose();
        file_stream.Dispose();
    }

    private void Update()
    {
        int set_index = -99;
        if (Input.GetKeyDown(KeyCode.Q)) set_index = 0;
        if (Input.GetKeyDown(KeyCode.W)) set_index = 1;
        if (Input.GetKeyDown(KeyCode.E)) set_index = 2;
        if (Input.GetKeyDown(KeyCode.R)) set_index = 3;
        if (set_index != -99) {
            SoundDistroy();
            SoundPlay(set_index);
            set_index = -99;
        }
    }


    private void OnApplicationQuit()
    {
        Debug.Log("OnApplicationQuit");
        SoundDistroy();
    }
}