2013-10-31 60 views

回答

1
using System.Runtime.InteropServices; 
    using MonoTouch.AudioToolbox; 

    public override void ViewDidLoad() 
    { 
     base.ViewDidLoad(); 
     . 
     . 
     . 
     AudioSession.Initialize(null, NSRunLoop.NSDefaultRunLoopMode); 
     AudioSession.AudioRouteChanged += AudioSession_AudioRouteChanged; 
    } 

    void AudioSession_AudioRouteChanged (object sender, AudioSessionRouteChangeEventArgs e) 
    { 
      if (e.CurrentOutputRoutes [0] == AudioSessionOutputRouteKind.Headphones) 
      { 
        //Code when is plugged 
      } 
      else 
      { 
        //Code when is unplugged       
      } 
    } 
2

事情是這樣的:

using System.Runtime.InteropServices; 
using MonoTouch.AudioToolbox; 

... 

public override void ViewDidLoad() 
{ 
    base.ViewDidLoad(); 
    AudioSession.AddListener(AudioSessionProperty.AudioRouteChange, EventHandler); 
} 

void EventHandler(AudioSessionProperty prop, int size, IntPtr data) 
{ 
    var isHeadphonesAvailable = IsHeadphonesAvailable (prop, size, data); 
    if (isHeadphonesAvailable) { 
     // Do something 
    } else { 
     // Do something else 
    } 
} 

bool IsHeadphonesAvailable(AudioSessionProperty prop, int size, IntPtr data) 
{ 
    var result = false; 
    if (prop == AudioSessionProperty.AudioRouteChange) { 
    var text = Marshal.PtrToStringAuto (data, size); 
    result = (text.Contains ("Head")); 
    } 
    return result; 
} 

沒有嘗試真正的設備上。只需轉換Objective-C片段之一即可。

+0

感謝您的回答,但代碼在iOS7中已過時 –

相關問題