I am reading samples from a software defined radio device that delivers two channels of Int16 (shorts) that represent audio. I am trying to send this stream to an audio output device on a PC.
I already have this working with a different set of tools but would like to use NAudio in its place since there are other capabilities I could use.
The code starts with the software defined radio method placing an array of shorts (i.e. int16) arranged as left channel then right channel. The array size is 65536, the sample rate is 192,000.
When the packet is received it is place on a Blocking collection to be picked up by a thread that sends out the audio.
So for the purpose of this question, the thread starts by reading the blocking collection which returns 65536 shorts.
StartStream = true;
waveformat = new WaveFormat(192000, 16, 2);
bs = new BufferedWaveProvider(waveformat);
bs.BufferLength = 65536 * 4;
_waveOut.DeviceNumber = 4;
while (true)
{
dspPacket = dsp_Queue.Take(); //take int16[] of queue
int j = 0;
try
{
for (int i = 0; i < 32768; i += 2)
{
byte[] qDataByte = BitConverter.GetBytes(dspShort[i]);
dspBytes[j] = qDataByte[0];
dspBytes[j + 1] = qDataByte[1];
j += 2;
}
if (startStream)
{
bs.AddSamples(dspBytes, 0, 65536);
_waveOut.Init(bs);
_waveOut.Play();
startStream = false;
}
else
{
bs.AddSamples(dspBytes, 0, 65536);
}
}
catch (Exception ex)
{
}
// SendData(dspPacket); //if this is uncommented, everything works correctly with the old method.
}
Now I can feed the output of the waveout device to a virtual audio cable which then feeds it into some spectrum analyser software and then this is what you will see with here:
When I use the old routines, I get a solid line and the sound does not break up.
So, am I doing something wrong here?
Thanks, Tom
There are two types of messages on the CAN bus. Those are broadcast message and default message. Currently, I'm using fifo0 for both the message(which works perfectly fine). But I would like to use fifo1 specially for broadcast message. Below is my initializing code
uint8 BspCan_RxFilterConfig(uint32 filterId, uint32 filterMask, uint8 filterBankId, uint8 enableFlag, uint8 fifoAssignment)
{
///\todo Add method for calculating filter on the fly
CAN_FilterTypeDef canBusFilterConfig;
FunctionalState filterEnableFlag = ENABLE;
if(enableFlag == 0)
{
filterEnableFlag = DISABLE;
}
else
{
filterEnableFlag = ENABLE;
}
/*Define filter used to determine if application needs to handle message on the CAN bus or if it should
ignore it. If the selected rx FIFO is changed, the rx functions in this module must also be updated.
Using mask mode with all bits set to "don't care"*/
canBusFilterConfig.FilterBank = filterBankId; //Identification of which of the filter banks to define.
canBusFilterConfig.FilterMode = CAN_FILTERMODE_IDMASK; //Sets whether to filter out messages based on a specific id or a list
canBusFilterConfig.FilterScale = CAN_FILTERSCALE_32BIT; //Sets the width of the filter, 32-bit width means filter applies to full range of std id, extended id, IDE, and RTR bits
canBusFilterConfig.FilterIdHigh = (0xFFFF0000 & filterId)>>16; //For upper 16 bits, dominant bit is expected (logic 0)
canBusFilterConfig.FilterIdLow = 0x0000FFFF & filterId; //For Lower 16 bits, dominant bit is expected (logic 0)
canBusFilterConfig.FilterMaskIdHigh = (0xFFFF0000 & filterMask)>>16; //Upper 16 bits are don't care
canBusFilterConfig.FilterMaskIdLow = 0x0000FFFF & filterMask; //Lower 16 bits are don't care
//canBusFilterConfig.FilterFIFOAssignment = CAN_FILTER_FIFO0; //Sets which rx FIFO to which to apply the filter settings
canBusFilterConfig.FilterActivation = filterEnableFlag;
canBusFilterConfig.SlaveStartFilterBank = 1; //Bank for the defined filter. Arbitrary value.
if (fifoAssignment == 0)
{
canBusFilterConfig.FilterFIFOAssignment = CAN_FILTER_FIFO0;
}
else
{
canBusFilterConfig.FilterFIFOAssignment = CAN_FILTER_FIFO1;
}
//Only fails if CAN peripheral is not in ready or listening state
if (HAL_CAN_ConfigFilter(&gCanBusH, &canBusFilterConfig) != HAL_OK)
{
return(ERR_CAN_INIT_FAILED);
}
else
{
return(SZW_NO_ERROR);
}
}//end BspCan_RxFilterConfig
When initializing, fifo0 works perfectly but fifo1 doesn't. If I just initialize fifo1 for both types of messages, it doesn't generate the interrupt. What am I doing wrong over here ? How to i initialize fifo1 to make it work and generate interrupt? I also tried without using digital filters still no luck.
Thanks in advance,
I ran the following code sample obtained from a tutorial here: http://www.dreamincode.net/forums/topic/148707-introduction-to-using-libusb-10/
I ran it against a tablet running Android 4 attached via USB to a MacBook Pro running Mac OS X Mountain Lion.
The output contained "Writing Successful!" so I assume libusb_bulk_transfer() worked correctly. My question is where did the 4 bytes of data got transferred to? Can I save it to a file on the Android tablet?
Thanks for your help!
#include <iostream>
#include <libusb.h>
using namespace std;
int main() {
libusb_device **devs; //pointer to pointer of device, used to retrieve a list of devices
libusb_device_handle *dev_handle; //a device handle
libusb_context *ctx = NULL; //a libusb session
int r; //for return values
ssize_t cnt; //holding number of devices in list
r = libusb_init(&ctx); //initialize the library for the session we just declared
if(r < 0) {
cout<<"Init Error "<<r<<endl; //there was an error
return 1;
}
libusb_set_debug(ctx, 3); //set verbosity level to 3, as suggested in the documentation
cnt = libusb_get_device_list(ctx, &devs); //get the list of devices
if(cnt < 0) {
cout<<"Get Device Error"<<endl; //there was an error
return 1;
}
cout<<cnt<<" Devices in list."<<endl;
dev_handle = libusb_open_device_with_vid_pid(ctx, 5118, 7424); //these are vendorID and productID I found for my usb device
if(dev_handle == NULL)
cout<<"Cannot open device"<<endl;
else
cout<<"Device Opened"<<endl;
libusb_free_device_list(devs, 1); //free the list, unref the devices in it
unsigned char *data = new unsigned char[4]; //data to write
data[0]='a';data[1]='b';data[2]='c';data[3]='d'; //some dummy values
int actual; //used to find out how many bytes were written
if(libusb_kernel_driver_active(dev_handle, 0) == 1) { //find out if kernel driver is attached
cout<<"Kernel Driver Active"<<endl;
if(libusb_detach_kernel_driver(dev_handle, 0) == 0) //detach it
cout<<"Kernel Driver Detached!"<<endl;
}
r = libusb_claim_interface(dev_handle, 0); //claim interface 0 (the first) of device (mine had jsut 1)
if(r < 0) {
cout<<"Cannot Claim Interface"<<endl;
return 1;
}
cout<<"Claimed Interface"<<endl;
cout<<"Data->"<<data<<"<-"<<endl; //just to see the data we want to write : abcd
cout<<"Writing Data..."<<endl;
r = libusb_bulk_transfer(dev_handle, (2 | LIBUSB_ENDPOINT_OUT), data, 4, &actual, 0); //my device's out endpoint was 2, found with trial- the device had 2 endpoints: 2 and 129
if(r == 0 && actual == 4) //we wrote the 4 bytes successfully
cout<<"Writing Successful!"<<endl;
else
cout<<"Write Error"<<endl;
r = libusb_release_interface(dev_handle, 0); //release the claimed interface
if(r!=0) {
cout<<"Cannot Release Interface"<<endl;
return 1;
}
cout<<"Released Interface"<<endl;
libusb_close(dev_handle); //close the device we opened
libusb_exit(ctx); //needs to be called to end the
delete[] data; //delete the allocated memory for data
return 0;
}
The libusb_bulk_transfer() function writes the data at the specified endpoint. Its an address, access it, print it, or you can copy it, do some case conversion and dump it to an outgoing endpoint. And, then perform a read through libusb_bulk_transfer()
I am new to iPhone. Could you please help me to modify the SpeakHere app from Apple to record in mono format. What should I have to set for mChannelsPerFrame and what else should I set?
I already change some part for record on linearPCM WAVE format.
Here is link to speakHere.
Here is what I think they allow me to change but I don't quite understand on sound:
void ChangeNumberChannels(UInt32 nChannels, bool interleaved)
// alter an existing format
{
Assert(IsPCM(), "ChangeNumberChannels only works for PCM formats");
UInt32 wordSize = SampleWordSize(); // get this before changing ANYTHING
if (wordSize == 0)
wordSize = (mBitsPerChannel + 7) / 8;
mChannelsPerFrame = nChannels;
mFramesPerPacket = 1;
if (interleaved) {
mBytesPerPacket = mBytesPerFrame = nChannels * wordSize;
mFormatFlags &= ~kAudioFormatFlagIsNonInterleaved;
} else {
mBytesPerPacket = mBytesPerFrame = wordSize;
mFormatFlags |= kAudioFormatFlagIsNonInterleaved;
}
}
On iPhone you will only be able to record in mono.
You shouldn't need to do anything to set this up in the SpeakHere example. It's done automatically. For example in AQRecorder::SetupAudioFormat:
size = sizeof(mRecordFormat.mChannelsPerFrame);
XThrowIfError(AudioSessionGetProperty( kAudioSessionProperty_CurrentHardwareInputNumberChannels,
&size,
&mRecordFormat.mChannelsPerFrame), "couldn't get input channel count");
That gets the supported hardware input channels and sets it as an ivar. Elsewhere, the buffer size calculations will factor that in.
Can credit card type be determined solely from the credit card number?
Is this recommended or should we always ask client for the type of credit card they're using?
I Googled about it and found this algorithm: http://cuinl.tripod.com/Tips/o-1.htm , is this reliable?
Yes, the site you mentioned is correct. Many sites, incl. Google Checkout I believe, rely on automatic detection of the card type. It's convenient, makes the UI less cluttered (one less input box) and saves time. Go ahead!
I have heard one good reason to make them pick (even though you can figure it out). So that they know the list of credit cards you accept.
As a consumer, I hate choosing a card first. I want to just start typing the number.
This issue is discussed in Wroblewski's Web Form Design on pages 153-154. It's in the section "Removing Questions" of the chapter "Unnecessary Inputs." The example given is Paypal, which highlights the type of card when you've typed in your number.
I am pretty certain that at least for MasterCard, Visa, Discover, and American Express that that is accurate. I have never worked with any of the others.
See the very bottom of this page:
http://www.merchantplus.com/resources/pages/credit-card-logos-and-test-numbers/
Also this might be useful to you"
http://www.beachnet.com/~hstiles/cardtype.html
This is pretty interesting to:
http://en.wikipedia.org/wiki/Bank_card_number
here is the script that i use that works with current card ranges. also does a validity check on the number.
/**
* checks a given string for a valid credit card
* #returns:
* -1 invalid
* 1 mastercard
* 2 visa
* 3 amex
* 4 diners club
* 5 discover
* 6 enRoute
* 7 jcb
*/
function checkCC(val) {
String.prototype.startsWith = function (str) {
return (this.match("^" + str) == str)
}
Array.prototype.has=function(v,i){
for (var j=0;j<this.length;j++){
if (this[j]==v) return (!i ? true : j);
}
return false;
}
// get rid of all non-numbers (space etc)
val = val.replace(/[^0-9]/g, "");
// now get digits
var d = new Array();
var a = 0;
var len = 0;
var cval = val;
while (cval != 0) {
d[a] = cval%10;
cval -= d[a];
cval /= 10;
a++;
len++;
}
if (len < 13)
return -1;
var cType = -1;
// mastercard
if (val.startsWith("5")) {
if (len != 16)
return -1;
cType = 1;
} else
// visa
if (val.startsWith("4")) {
if (len != 16 && len != 13)
return -1;
cType = 2;
} else
// amex
if (val.startsWith("34") || val.startsWith("37")) {
if (len != 15)
return -1;
cType = 3;
} else
// diners
if (val.startsWith("36") || val.startsWith("38") || val.startsWith("300") || val.startsWith("301") || val.startsWith("302") || val.startsWith("303") || val.startsWith("304") || val.startsWith("305")) {
if (len != 14)
return -1;
cType = 4;
} else
// discover
if (val.startsWith("6011")) {
if (len != 15 && len != 16)
return -1;
cType = 5;
} else
// enRoute
if (val.startsWith("2014") || val.startsWith("2149")) {
if (len != 15 && len != 16)
return -1;
// any digit check
return 6;
} else
// jcb
if (val.startsWith("3")) {
if (len != 16)
return -1;
cType = 7;
} else
// jcb
if (val.startsWith("2131") || val.startsWith("1800")) {
if (len != 15)
return -1;
cType = 7;
} else
return - 1;
// invalid cc company
// lets do some calculation
var sum = 0;
var i;
for (i = 1; i < len; i += 2) {
var s = d[i] * 2;
sum += s % 10;
sum += (s - s%10) /10;
}
for (i = 0; i < len; i += 2)
sum += d[i];
// musst be %10
if (sum%10 != 0)
return - 1;
return cType;
}
Here's Complete C# or VB code for all kinds of CC related things on codeproject.
IsValidNumber
GetCardTypeFromNumber
GetCardTestNumber
PassesLuhnTest
This article has been up for a couple years with no negative comments.
Wikipedia contains a list of most card prefixes. Some cards are missing from the link you posted. It also appears that the link you provided is valid.
One reason to ask for the card type is for extra validation, compare what the user provided against the number.
This is the php version of same algorithm mentioned in 1st post
<?php
function CreditCardType($CardNo)
{
/*
'*CARD TYPES *PREFIX *WIDTH
'American Express 34, 37 15
'Diners Club 300 to 305, 36 14
'Carte Blanche 38 14
'Discover 6011 16
'EnRoute 2014, 2149 15
'JCB 3 16
'JCB 2131, 1800 15
'Master Card 51 to 55 16
'Visa 4 13, 16
*/
//Just in case nothing is found
$CreditCardType = "Unknown";
//Remove all spaces and dashes from the passed string
$CardNo = str_replace("-", "",str_replace(" ", "",$CardNo));
//Check that the minimum length of the string isn't less
//than fourteen characters and -is- numeric
If(strlen($CardNo) < 14 || !is_numeric($CardNo))
return false;
//Check the first two digits first
switch(substr($CardNo,0, 2))
{
Case 34: Case 37:
$CreditCardType = "American Express";
break;
Case 36:
$CreditCardType = "Diners Club";
break;
Case 38:
$CreditCardType = "Carte Blanche";
break;
Case 51: Case 52: Case 53: Case 54: Case 55:
$CreditCardType = "Master Card";
break;
}
//None of the above - so check the
if($CreditCardType == "Unknown")
{
//first four digits collectively
switch(substr($CardNo,0, 4))
{
Case 2014:Case 2149:
$CreditCardType = "EnRoute";
break;
Case 2131:Case 1800:
$CreditCardType = "JCB";
break;
Case 6011:
$CreditCardType = "Discover";
break;
}
}
//None of the above - so check the
if($CreditCardType == "Unknown")
{
//first three digits collectively
if(substr($CardNo,0, 3) >= 300 && substr($CardNo,0, 3) <= 305)
{
$CreditCardType = "American Diners Club";
}
}
//None of the above -
if($CreditCardType == "Unknown")
{
//So simply check the first digit
switch(substr($CardNo,0, 1))
{
Case 3:
$CreditCardType = "JCB";
break;
Case 4:
$CreditCardType = "Visa";
break;
}
}
return $CreditCardType;
}
?>
The code you linked has an incomplete BIN/range list for Discover, omits Diner's club (which now belongs to Discover anyway), lists card types that no longer exist and should be folded into other types (enRoute, Carte Blanche), and ignores the increasingly-important Maestro International cart type.
As #Alex confirmed, it's possible to determine the card type from the BIN number, and numerous companies do it but doing so consistently and correctly is not trivial: card brands constantly change, and keeping track of things becomes more complicated as you try to handle regional debit cards (Laser in Ireland, Maestro in Europe, etc) - I have not found a free and maintained (correct) piece of code or algorithm for this anywhere.
As #MitMaro poined out, Wikipedia contains a high-level list of card identifiers, and also a more-specific list of BIN numbers and ranges, which is a good start, and as gbjbaanb commented, Barclays has a publically-published list (but it does not seem to include Discover for some reason - presumably they don't process on the Discover network?)
Trivial as it may seem, a correct card-identification algorithm/method/function takes work to maintain, so unless your detection routine is non-critical/informational (eg #Simon_Weaver's suggestion), OR you're going to put in the work to keep it current, I would recommend that you skip the automatic detection.
Stripe has provided this fantastic javascript library for card scheme detection. Let me add few code snippets and show you how to use it.
Firstly Include it to your web page as
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.payment/1.2.3/jquery.payment.js " ></script>
Secondly use the function cardType for detecting the card scheme.
$(document).ready(function() {
var type = $.payment.cardType("4242 4242 4242 4242"); //test card number
console.log(type);
});
Here are the reference links for more examples and demos.
Stripe blog for jquery.payment.js
Github repository
Here's a quick a dirty way to determine the card type automatically and show it to the user while they're typing.
That means
a) the user doesnt have to pick it and
b) they wont waste time looking for a dropdown that doesnt exist.
Very simple jQuery version for Amex, Visa and Mastercard.
if you need other card types you can take the
$('[id$=CreditCardNumber]').assertOne().keyup(function(){
// rules taken from http://en.wikipedia.org/wiki/Credit_card_number#cite_note-GenCardFeatures-0
var value = $(this).val();
$('#ccCardType').removeClass("unknown");
if ((/^4/).test(value)) {
$('#ccCardType').html("Visa");
return;
}
if ((/^5[1-5]/).test(value)) {
$('#ccCardType').html("Mastercard");
return;
}
if ((/^3[47]/).test(value)) {
$('#ccCardType').html("Mastercard");
return;
}
$('#ccCardType').html("Enter card number above");
$('#ccCardType').addClass("unknown");
});
This is the jQuery to accompany this (ASP.NET MVC):
Card number: <%= Html.TextBox("PaymentDetails.CreditCardDetails.CreditCardNumber")%>
Card Type: <span id="ccCardType" class="unknown">Enter card number above</span>
I have a css rule for .unknown to display grayed out text.
This implementation in Python should work for AmEx, Discover, Master Card, Visa:
def cardType(number):
number = str(number)
cardtype = "Invalid"
if len(number) == 15:
if number[:2] == "34" or number[:2] == "37":
cardtype = "American Express"
if len(number) == 13:
if number[:1] == "4":
cardtype = "Visa"
if len(number) == 16:
if number[:4] == "6011":
cardtype = "Discover"
if int(number[:2]) >= 51 and int(number[:2]) <= 55:
cardtype = "Master Card"
if number[:1] == "4":
cardtype = "Visa"
return cardtype
If all the credit cards that you accept have the same properties then just let the user enter the card number and other properties (expiry date, CVV, etc). However, some card types require different fields to be entered (e.g. start date or issue number for UK Maestro cards). In those cases, you either have to have all fields, thereby confusing the user, or some Javascript to hide/show the relevant fields, again making the user experience a bit weird (fields disappearing/appearing, as they enter the credit card number). In those cases, I recommend asking for the card type first.
Personally I have no problem with picking the card type first. But there are two aspects of credit card number entry that are problematic in my view.
The worst is the inability to enter spaces between groups of numbers. Including the spaces printed on the physical cards would make the digits vastly easier for the user to scan to verify they've entered the information correctly. Every time I encounter this ubiquitous deficiency I feel like I'm being propelled backwards into a stone age when user input couldn't be filtered to remove unnecessary characters.
The second is the need when placing a phone order to listen to the vendor repeat the card number back to you. All the credit card recipient actually needs is a UI that gives them access to the check digit scheme which verifies that a cc number is valid. According to that algorithm the first 15 (or however many) digits calculate the last digit - and is virtually impossible to "fool." For a fat fingered number to "pass" requires at least two mutually canceling errors among the 15 digits. Unless the algorithm suffers from the defect of being dis-proportionally fooled by transposing adjacent numbers (a common entry error) which I doubt, I except it is more reliable than any human double check.
https://binlist.net/ offers a free API. You only need to enter the first 6 or 8 digits of the card number - i.e. the Issuer Identification Numbers (IIN), previously known as Bank Identification Number (BIN).
curl -H "Accept-Version: 3" "https://lookup.binlist.net/45717360"
NPM: https://www.npmjs.com/package/binlookup
Source: https://github.com/paylike/binlookup
(cross-posted from a more specific question: How tell the difference between a Debit Card and a Credit Card )