xref: /haiku/src/tests/kits/media/playwav/playwav.cpp (revision ecba909c8ce258df90744f9845b0ffecb15fb896)
1 #include <Application.h>
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <fcntl.h>
5 #include <OS.h>
6 
7 #define USE_NEW_PLAYER 0
8 
9 #if USE_NEW_PLAYER
10   #define NAMESPACE	BExperimental::
11   #include "NewSoundPlayer.h"
12 #else
13   #define NAMESPACE
14   #include <SoundPlayer.h>
15 #endif
16 
17 #define FILENAME "/boot/home/test1.wav"
18 #define SIZE	2048
19 
20 port_id port = -1;
21 sem_id finished = -1;
22 int fd = -1;
23 NAMESPACE BSoundPlayer *sp = 0;
24 
PlayBuffer(void * cookie,void * buffer,size_t size,const media_raw_audio_format & format)25 void PlayBuffer(void *cookie, void * buffer, size_t size, const media_raw_audio_format & format)
26 {
27 	size_t portsize = port_buffer_size(port);
28 	int32 code;
29 
30 	read_port(port, &code, buffer, portsize);
31 
32 	if (size != portsize) {
33 		sp->SetHasData(false);
34 		release_sem(finished);
35 	}
36 }
37 
filereader(void * arg)38 int32 filereader(void *arg)
39 {
40 	char buffer[SIZE];
41 	int size;
42 
43 	printf("file reader started\n");
44 
45 	for (;;) {
46 		size = read(fd, buffer, SIZE);
47 		write_port(port, 0, buffer, size);
48 		if (size != SIZE)
49 			break;
50 	}
51 
52 	write_port(port, 0, buffer, 0);
53 
54 	printf("file reader finished\n");
55 
56 	return 0;
57 }
58 
main(int argc,char * argv[])59 int main(int argc, char *argv[])
60 {
61 	fd = open((argc > 1) ? argv[1] : FILENAME, O_RDONLY);
62 	if (fd < 0)
63 		return -1;
64 
65 	lseek(fd, 44, SEEK_SET); // skip wav header
66 
67 	new BApplication("application/x-vnd.playfile");
68 	finished = create_sem(0, "finish wait");
69 	port = create_port(64, "buffer");
70 
71 	media_raw_audio_format format;
72 	format = media_raw_audio_format::wildcard;
73 	format.frame_rate = 44100;
74 	format.channel_count = 2;
75 	format.format = media_raw_audio_format::B_AUDIO_SHORT;
76 	format.byte_order = B_MEDIA_LITTLE_ENDIAN;
77 	format.buffer_size = 2048;
78 
79 	printf("spawning reader thread...\n");
80 
81 	resume_thread(spawn_thread(filereader, "filereader", 8, 0));
82 
83 	snooze(1000000);
84 
85 	printf("playing soundfile...\n");
86 
87 	sp = new NAMESPACE BSoundPlayer(&format, "sound player test", PlayBuffer);
88 
89 	sp->SetHasData(true);
90 	sp->Start();
91 
92 	sp->SetVolume(1.0f);
93 
94 	// wait for playback end
95 	acquire_sem(finished);
96 
97 	printf("\nplayback finished\n");
98 
99 	delete sp;
100 
101 	close(fd);
102 }
103