Last active
December 8, 2019 09:19
-
-
Save geilt/9e06b0ea212c88457e99140abc24a1ee to your computer and use it in GitHub Desktop.
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
/* | |
global navigator | |
*/ | |
function checkAudio(){ | |
var iOS = [ 'iPad', 'iPhone', 'iPod' ].indexOf( navigator.platform ) >= 0; | |
var microphone, speakers; | |
if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) { | |
console.error( 'checkAudio', "enumerateDevices() not supported."); | |
return Promise.resolve( false ); | |
} | |
return navigator.mediaDevices.getUserMedia( { audio: true } ) | |
.then( stream => { | |
stream.getTracks().forEach( function( track ) { | |
track.stop(); | |
}); | |
return navigator.mediaDevices.enumerateDevices(); | |
}) | |
.then( devices => { | |
var hasMic = false; | |
var hasSpeakers = false; | |
devices.forEach( device => { | |
devices[device.kind][device.deviceId] = device; | |
if( device.kind == 'audiooutput' ) { | |
hasSpeakers = true; | |
if( device.deviceId == 'default' ) speakers = device; | |
} | |
if( device.kind == 'audioinput' ){ | |
hasMic = true; | |
if( device.deviceId == 'default' ) microphone = device; | |
if( device.label == 'iPad Microphone' ) { | |
hasSpeakers = true; // Fix for iPadOS since it now considered it a freaking Mac... | |
iOS = true; | |
} | |
} | |
}); | |
if( iOS ) hasSpeakers = true; | |
if( microphone !== null && speakers !== null ) return true; | |
if( hasMic !== false && hasSpeakers !== false ) return true; | |
if( !hasMic ) console.error( 'checkAudio', 'Microphone Missing! Check to see if your headset is plugged in.' ); | |
if( !hasSpeakers ) console.error( 'checkAudio', 'Speakers Missing! Check to see if your headset is plugged in.' ); | |
return false; | |
}) | |
.catch( err => { | |
console.warn( 'checkAudio', 'Audio Error', err.name + ": " + err.message ); | |
return false; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code is useful to make sure your client has speakers and microphone for using things like WebRTC Phones.
Also solves an issue with iOS. If you use this function before starting a WebRTC Session, iOS will consider it's devices initialized, so the phone should work. What happens is that on the first request for Audio Media whe initializing a webphone, the system sometimes doesn't detect the Audio devices as being initliazlied or there.
This also works with the new iPadOS which identifies as a Mac, we do this by checking for the Device that says iPad Microphone.
We also assume that Speakers exist on iPad's, since they don't detect properly.