xref: /haiku/src/tests/kits/game/push_game_sound_test/push_game_sound_sine.cpp (revision 25a7b01d15612846f332751841da3579db313082)
1 /*
2  * Copyright 2012, Adrien Destugues <pulkomandy@gmail.com>
3  * Distributed under the terms of the MIT License.
4  */
5 
6 
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 
11 #include <Entry.h>
12 #include <InterfaceDefs.h>
13 #include <MediaFile.h>
14 #include <MediaTrack.h>
15 #include <PushGameSound.h>
16 
17 
18 int
main(int argc,char * argv[])19 main(int argc, char *argv[])
20 {
21 	// 256 frames * 4 buffer parts * 2 channels * 2 bytes per sample
22 	// will give us internal buffer of 4096 bytes
23 	size_t framesPerBufferPart = 256;
24 	size_t bufferPartCount = 4;
25 
26 	if (argc != 1 && argc != 3) {
27 		printf("Usage: %s [<frames per part> <parts>]\n",
28 			argv[0]);
29 		return 0;
30 	}
31 
32 	if (argc == 3) {
33 		size_t size = strtoul(argv[1], NULL, 10);
34 		if (size > 0)
35 			framesPerBufferPart = size;
36 
37 		size = strtoul(argv[2], NULL,  10);
38 		if (size > 0)
39 			bufferPartCount = size;
40 	}
41 
42 	printf("frames per buffer part: %ld\n", framesPerBufferPart);
43 	printf("buffer part count: %ld\n", bufferPartCount);
44 
45 	gs_audio_format gsFormat;
46 	memset(&gsFormat, 0, sizeof(gsFormat));
47 	gsFormat.frame_rate = 48000;
48 	gsFormat.channel_count = 1;
49 	gsFormat.format = gs_audio_format::B_GS_S16;
50 	gsFormat.byte_order = B_MEDIA_LITTLE_ENDIAN;
51 	gsFormat.buffer_size = framesPerBufferPart;
52 
53 	BPushGameSound pushGameSound(framesPerBufferPart, &gsFormat,
54 		bufferPartCount);
55 	if (pushGameSound.InitCheck() != B_OK) {
56 		printf("trouble initializing push game sound: %s\n",
57 			strerror(pushGameSound.InitCheck()));
58 		return 1;
59 	}
60 
61 	uint8 *buffer;
62 	size_t bufferSize;
63 	if (pushGameSound.LockForCyclic((void **)&buffer, &bufferSize)
64 			!= BPushGameSound::lock_ok) {
65 		printf("cannot lock buffer\n");
66 		return 1;
67 	}
68 	memset(buffer, 0, bufferSize);
69 
70 	if (pushGameSound.StartPlaying() != B_OK) {
71 		printf("cannot start playback\n");
72 		return 1;
73 	}
74 
75 	printf("playing, press [esc] to exit...\n");
76 
77 	key_info keyInfo;
78 
79 	size_t sampleCount = framesPerBufferPart * bufferPartCount;
80 	for(size_t pos = 0; pos < sampleCount; pos++)
81 	{
82 		*(int16_t*)(buffer + pos * sizeof(int16_t))
83 			= (int16_t)(2000 * sin(pos * gsFormat.frame_rate
84 					/ ((float)sampleCount * 440)));
85 	}
86 
87 	while (true) {
88 		usleep(1000000 * framesPerBufferPart / gsFormat.frame_rate);
89 
90 		// check escape key state
91 		if (get_key_info(&keyInfo) != B_OK) {
92 			printf("\nkeyboard state read error\n");
93 			break;
94 		}
95 		if ((keyInfo.key_states[0] & 0x40) != 0)
96 			break;
97 	}
98 
99 	pushGameSound.StopPlaying();
100 
101 	printf("\nfinished.\n");
102 
103 	return 0;
104 }
105