2016-08-18 56 views
0

當音頻會話以NAudio開始和結束時,我希望收到回調。以下代碼正在工作:使用NAudio爲狀態更改接收音頻會話回調

private void SetupMediaSessionCallbacks() 
    { 
     // Foreach output endpoint 
     foreach (var md in new MMDeviceEnumerator().EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active)) 
     { 
      md.AudioSessionManager.OnSessionCreated += OnSessionCreated; 
     } 
    } 

此代碼在創建新音頻會話時觸發。我是新來的n音訊,所以我不知道如何設置RegisterEventClient接收狀態更改事件:

private void OnSessionCreated(object sender, IAudioSessionControl newSession) 
    { 
     // Not working, need help here! 
     AudioSessionControl audioSession = new AudioSessionControl(newSession); 
     IAudioSessionEventsHandler handler = null; 
     AudioSessionEventsCallback notifications = new AudioSessionEventsCallback(test); 
     handler.OnStateChanged += new EventHandler<AudioSessionState>(notifications_StateChanged); 
     audioSession.RegisterEventClient(handler); 
    } 

這裏的回調,我相信這是正確的:

void notifications_StateChanged(object sender, AudioSessionState newState) 
    { 
     if (newState == AudioSessionState.AudioSessionStateActive) 
     { 
      Console.WriteLine("StateChanged"); 
     } 
    } 

任何幫助將不勝感激。我已經搜索了這個文件的高和低。

回答

1

想通了。我需要創建自己的繼承自IAudioSessionEventsHandler的類。這裏是OnSessionCreated的代碼:

private void OnSessionCreated(object sender, IAudioSessionControl newSession) 
{ 
    AudioSessionControl audioSession = new AudioSessionControl(newSession); 
    NAudioEventCallbacks callbacks = new NAudioEventCallbacks(); 
    AudioSessionEventsCallback notifications = new AudioSessionEventsCallback(callbacks); 
    audioSession.RegisterEventClient(callbacks); 

} 

public class NAudioEventCallbacks : IAudioSessionEventsHandler 
{ 
    public void OnChannelVolumeChanged(uint channelCount, IntPtr newVolumes, uint channelIndex) { } 

    public void OnDisplayNameChanged(string displayName) { } 

    public void OnGroupingParamChanged(ref Guid groupingId) { } 

    public void OnIconPathChanged(string iconPath) { } 

    public void OnSessionDisconnected(AudioSessionDisconnectReason disconnectReason) { } 

    public void OnStateChanged(AudioSessionState state) { } 

    public void OnVolumeChanged(float volume, bool isMuted) { } 
} 

我現在可以在NAudioEventCallbacks中設置符合預期的斷點。