Skip to content

Instantly share code, notes, and snippets.

@geilt
Last active December 8, 2019 09:19
Show Gist options
  • Save geilt/9e06b0ea212c88457e99140abc24a1ee to your computer and use it in GitHub Desktop.
Save geilt/9e06b0ea212c88457e99140abc24a1ee to your computer and use it in GitHub Desktop.
/*
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;
});
}
@geilt
Copy link
Author

geilt commented Dec 8, 2019

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment