I try to play audio buffer in windows phone app.
byte[] buffer = new byte[44100 * 2 * 5];
float t = 0;
for (int i = 0; i < 44100 * 2 * 5; i += 2)
{
short val = (short)(Math.Sin(t * 2 * Math.PI * 440) * short.MaxValue);
buffer[i] = (byte)(val & 0xFF);
buffer[i + 1] = (byte)(val >> 8);
t += 1 / 44100.0f;
}
sf = new SoundEffect(buffer, 44100, AudioChannels.Mono);
// Play.
sf.Play();
i get error:
A first chance exception of type 'System.InvalidOperationException' occurred in Microsoft.Xna.Framework.ni.dll
An exception of type 'System.InvalidOperationException' occurred in Microsoft.Xna.Framework.ni.dll but was not handled in user code
Help pls!
You need to call the FrameworkDispatcher.Update.
Same answer as here should work:
Playing a sound from a generated buffer in a Windows phone app
Related
I am working on a project to write to and read from a TP Link / Kaza power strip or smart plug.
The data that is sent is encrypted json that has been "autokey encrypted".
So far I have been able to convert a typescript encrypt function and it works well. I get the expected result. However, I need to add a "header" to my encrypted data. That data is 3 null bytes followed by a byte that is a measure of the length of the encrypted bytes.
The typescript example has this bit of code to "encrypt with headers", however, I've hit a bit of a wall trying to convert it to something usable. Can someone nudge me along the path ?
First are the two typescript functions: (borrowed from https://github.com/plasticrake/tplink-smarthome-crypto/blob/master/src/index.ts)
/**
* Encrypts input where each byte is XOR'd with the previous encrypted byte.
*
* #param input - Data to encrypt
* #param firstKey - Value to XOR first byte of input
* #returns encrypted buffer
*/
export function encrypt(input: Buffer | string, firstKey = 0xab): Buffer {
const buf = Buffer.from(input);
let key = firstKey;
for (let i = 0; i < buf.length; i += 1) {
// eslint-disable-next-line no-bitwise
buf[i] ^= key;
key = buf[i];
}
return buf;
}
/**
* Encrypts input that has a 4 byte big-endian length header;
* each byte is XOR'd with the previous encrypted byte.
*
* #param input - Data to encrypt
* #param firstKey - Value to XOR first byte of input
* #returns encrypted buffer with header
*/
export function encryptWithHeader(
input: Buffer | string,
firstKey = 0xab
): Buffer {
const msgBuf = encrypt(input, firstKey);
const outBuf = Buffer.alloc(msgBuf.length + 4);
outBuf.writeUInt32BE(msgBuf.length, 0);
msgBuf.copy(outBuf, 4);
return outBuf;
}
Second is what I have so far.
// This part works well and produces the expected results
String encrypt(String input)
{
int16_t firstKey = 0xab;
String buf;
int key;
int i;
buf = input;
key = firstKey;
i = 0;
for (;i < buf.length();(i = i + 1))
{
buf[i] ^= key;
key = buf[i];
}
return buf;
}
// This does not function yet, as I'm pretty lost..
// This was orginally converted from typescript with https://andrei-markeev.github.io/ts2c/
// I started work on converting this, but ran into errors I don't know how to solve.
String encryptWithHeader(String input){
String msgBuf;
String outBuf;
int16_t firstKey = 0xab;
char * null = NULL;
msgBuf = encrypt(input);
outBuf = msgBuf.length() +1;
//this is where I got lost...
assert(null != NULL);
null[0] = '\0';
strncat(null, outBuf, msgBuf.length());
str_int16_t_cat(null, 4);
outBuf = msgBuf + 4
return outBuf;
}
Finally, the data:
//this is the unencrypted json
String offMsg = "{\"system\":{\"set_relay_state\":{\"state\":0}}}";
//current encrypt function produces:
d0f281f88bff9af7d5ef94b6c5a0d48bf99cf091e8b7c4b0d1a5c0e2d8a381f286e793f6d4eedea3dea3
//the working "withheaders" should produce:
00002ad0f281f88bff9af7d5ef94b6c5a0d48bf99cf091e8b7c4b0d1a5c0e2d8a381f286e793f6d4eedea3dea3
Admittedly my C/C++ ability is very limited and I can spell typescript, that's about all. I have a very extensive history with PHP. As useful as that is. So, I understand the basics of data structures and whatnot, but I'm venturing off into areas I've never been in. Any help would be greatly appreciated.
It looks like the encryption is fairly simple: write the current character XORed with the key to the buffer and make that newly written character the new key. It also looks like the "withHeaders" version adds the length of the encrypted string as a 4 byte integer to the start of the buffer. I think it might be easier to allocate a character array and pass that array to a function that writes the result to that buffer. For example:
void encryptWithHeader(byte buffer[], int bufferLength, byte key, String message) {
int i;
uint32_t messageLength = message.length();
Serial.println(message);
Serial.println(message.length());
// check that we won't overrun the buffer
if ( messageLength + 5 < bufferLength) {
buffer[0] = messageLength >> 24 & 0xFF;
buffer[1] = messageLength >> 16 & 0xFF;
buffer[2] = messageLength >> 8 & 0xFF;
buffer[3] = messageLength & 0xFF;
for (i = 0; i < messageLength; i++) {
buffer[i + 4] = message[i] ^ key;
key = buffer[i + 4];
}
}
else { // we would have overrun the buffer
Serial.println("not enough room in buffer for message");
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
byte theBuffer[64];
int i;
String offMsg = "{\"system\":{\"set_relay_state\":{\"state\":0}}}";
encryptWithHeader(theBuffer, 64, 0xab, offMsg);
// now print it out to check
for (i = 0; i < offMsg.length() + 4; i++) {
if (theBuffer[i] < 0x10) // adds an extra zero if a byte prints as on1y 1 char
Serial.print("0");
Serial.print(theBuffer[i], HEX);
}
while (true)
;
}
If you want to send the character buffer to a remote device you can send it out one byte at a time:
for (i = 0; i < offMsg.length() + 4; i++)
Serial.write(theBuffer[i]);
A game I am currently developing uses a 5x5 matrix to change the colors of the image on a per pixel basis. I was wondering if anyone has developed an extremely fast algorithm for something like this.
For every Pixel(setPixel(sourcePixel * Matrix))
I have built my own algorithm for this by getting and setting pixels on pixmap then drawing a new pixmap from this through iterating every pixel with set/get pixel. I have found a reasonably fast algorithm for this (150 million pixels ~3 seconds), but I was thinking of another idea rather than using the pixmap but I am unsure of how to implement this. Libgdx provides a FileHandle.readBytes() method that reads image files (in my case PNG) to byte arrays. My thought was rather than creating a pixmap, read the byte array while iterating the pixels. While iterating I would be drawing a new pixmap meaning their really is no point for me to make one for the base pixmap in the first place. With tests I found that with my current algorithm, 70% of the time it takes is from the method (PixMap.getPixel(x, y), and I could bypass this by straight reading the byte array. I have looked into PNG readers for byte array's online but to no avail.
Note I am unable to use ImageIO due it being an android based game. Would it make it faster by reading the byte array data while iterating/ is it possible to do this?
In the code below, JList is basically a HashMap in this context
private static JList<Integer, Pixmap> colorShiftImage(Pixmap p, JList<Integer, float[][]> cms){
JList<float[][], Pixmap> tempList = new JList<>();
for(int i = cms.size() - 1; i > -1; --i){
tempList.add(cms.getInt(i), new Pixmap(p.getWidth(), p.getHeight(), Pixmap.Format.RGBA8888));
}
for(int y = p.getHeight() - 1; y > -1; --y){
for(int x = p.getWidth() - 1; x > -1; --x){
int v = p.getPixel(x, y);
if(v != 0) {
r = ((v & 0xff000000) >>> 24);
g = ((v & 0x00ff0000) >>> 16);
b = ((v & 0x0000ff00) >>> 8);
a = ((v & 0x000000ff));
for(int i = tempList.size() - 1; i > -1; --i) {
float[][] c = tempList.getIDList().get(i);
tempList.getInt(i).drawPixel(x, y, (((l((r * c[0][0]) + (c[1][0] * g) + (c[2][0] * b) + (c[3][0] * a) + c[4][0])) << 24)
| ((l((r * c[0][1]) + (c[1][1] * g) + (c[2][1] * b) + (c[3][1] * a) + c[4][1])) << 16)
| ((l((r * c[0][2]) + (c[1][2] * g) + (c[2][2] * b) + (c[3][2] * a) + c[4][2])) << 8)
| ((l((r * c[0][3]) + (c[1][3] * g) + (c[2][3] * b) + (c[3][3] * a) + c[4][3])))));
}
}
}
}
JList<Integer, Pixmap> returnL = new JList<>();
for(int i = tempList.size() - 1; i > - 1; --i){
returnL.add(cms.getIDList().get(i), tempList.getInt(i));
}
return returnL;
}
public static int l(float v){
if(v < 0)return 0;
else if(v > 255)return 255;
return (int) v;
}
Its work fine when i set delay 20 but wav file playing slowly in some systems with windows 10.
private static void waveSourceAgent_DataAvailable(object sender, WaveInEventArgs e)
{
int delay = 10;
recordedMsgBuffer = RECORDING_BUFFER[0].recordedMsgBuffer;
int iterations = recordedMsgBuffer.Length / 320;
int remainingBytes = recordedMsgBuffer.Length % 320;
byte[] buffer = new byte[320];
for (int i = 0; i < iterations; i++)
{
byte[] tempbuff = new byte[320];
for (int j = 0; j < 320; j++)
{
tempbuff[j] = recordedMsgBuffer[(i * 320) + j];
}
if (waveProviderReciever != null)
waveProviderReciever.AddSamples(tempbuff, 0, tempbuff.Length);
Thread.Sleep(delay);
}
Looks like you are trying to play data that's being received (but not sure exactly how - you're not using the DataAvailable args) by putting it into a BufferedWaveProvider.
The secret to this working is that the speed at which audio is being placed into the buffer should match the speed it is being read out. If the WaveFormat of record and playback match (which they need to for this to work) then the buffer should never fill up unless playback has unexpectedly stopped.
If you are receiving data much faster than you are playing it (e.g. you are downloading a pre-recorded audio file), then you either need to increase the buffer size, or hold off putting any new data into the buffer until there is more space available.
windows phone 8 using visual studio
I'm trying to crop an image to 81 piece after i captured it through mobile cam but i found this exception. any help??
int halfWidth = (App.CroppedImage.PixelWidth / 9);
int halfHeight =(App.CroppedImage.PixelHeight / 9);
for (int row = 0; row < 9; row++)
for (int col = 0; col < 9; col++)
{
WriteableBitmap wr = App.CroppedImage.Crop(col * halfHeight, row * halfWidth, halfWidth, halfHeight);
MediaLibrary MLibrary = new MediaLibrary();
IsolatedStorageFileStream IsoStoreFileStreams = myStore.CreateFile("test"+row+col+".jpg");
Extensions.SaveJpeg(wr, IsoStoreFileStreams, 100, 100, 0, 85);
IsoStoreFileStreams.Close();
IsoStoreFileStreams = myStore.OpenFile("test"+ row + col +".jpg", FileMode.Open, FileAccess.Read);
//Add the JPEG file to the photos library on the device.
MediaLibrary libraryy = new MediaLibrary();
Picture picc = library.SavePicture("Saved"+row+col+".jpg", IsoStoreFileStreams);
IsoStoreFileStreams.Close();
}
the exception in this function
Extensions.SaveJpeg(wr, IsoStoreFileStreams, 100, 100, 0, 85);
and the message is
An exception of type 'System.ArgumentException' occurred in Microsoft.Phone.ni.dll but was not handled in user code
stack
sorry i found my error it was `
WriteableBitmap wr = App.CroppedImage.Crop(col * halfWidth, row * halfHeight, halfWidth, halfHeight);
instead
WriteableBitmap wr = App.CroppedImage.Crop(col * halfHeight, row * halfWidth, halfWidth, halfHeight);
`
What is the best way to debug a CRASHING flash app ? (no exception, my application just crash)
I am actualy facing a big problem: my app (full-flash website) was working fine with the flashplayer 9 but crash with the flashplayer 10...
Here is the BAD method who crash my app with FP10.
After removing the call to this method everything was working properly with FP10.
public static function drawWedgeCrown(g : Graphics,a : Number,r : Number,r2 : Number, n : Number, c : Number, t : Number) : void {
var x : Number ;
var y : Number;
g.beginFill(c, t);
g.moveTo(r, 0);
g.lineTo(r, 0);
var teta : Number = 0;
var dteta : Number = 2 * Math.PI / n;
while(teta < a) {
x = r * Math.cos(teta);
y = -r * Math.sin(teta);
g.lineTo(x, y);
teta += dteta;
}
x = r * Math.cos(a);
y = -r * Math.sin(a);
g.lineTo(x, y);
x = r2 * Math.cos(a);
y = -r2 * Math.sin(a);
g.lineTo(x, y);
teta = a;
dteta = 2 * Math.PI / n;
var cpt : int = 0;
while(teta > 0) {
cpt++;
x = r2 * Math.cos(teta);
y = -r2 * Math.sin(teta);
g.lineTo(x, y);
teta -= dteta;
}
x = r2 * Math.cos(0);
y = -r2 * Math.sin(0);
g.lineTo(x, y);
g.lineTo(r, 0);
g.endFill();
}
OK, i finaly found the real PROBLEM... it was not the method in it self.
I was passing NaN for the "A" argument causing an infinite loop...
Have you tried running it with the debugger? Set a breakpoint at the entry of your app and then step through it until it crashes. This way you can see which line of code is responsible and the state of the variables. Of course the actual problem might be something that happens prior but at least you have narrowed down your search and can trace backwards.
Also another way is to put some trace() statements in your code and see if the section ever gets hit. Then you can tell if its happening before or after and repeat until you find the problem area.