File: sdl_audio_panning.c

package info (click to toggle)
emscripten 3.1.6~dfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 114,112 kB
  • sloc: ansic: 583,052; cpp: 391,943; javascript: 79,361; python: 54,180; sh: 49,997; pascal: 4,658; makefile: 3,426; asm: 2,191; lisp: 1,869; ruby: 488; cs: 142
file content (89 lines) | stat: -rw-r--r-- 2,054 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
 * Copyright 2014 The Emscripten Authors.  All rights reserved.
 * Emscripten is available under two separate licenses, the MIT license and the
 * University of Illinois/NCSA Open Source License.  Both these licenses can be
 * found in the LICENSE file.
 */

#include <stdio.h>
#include <stdlib.h>
#include <SDL/SDL.h>
#include <SDL/SDL_mixer.h>
#include <assert.h>
#include <emscripten.h>
#include <math.h>
#include <sys/stat.h>

Mix_Chunk *sound;

void done() {
  REPORT_RESULT(1);
}

void pan() {
  static int frames = 0;
  frames++;

  float x = (sin(frames / 30.f) + 1) / 2;

  int channel = 0;
  int left = x * 255;
  int right = (1 - x) * 255;
  printf("%f %d %d\n", x, left, right);
  int panning = Mix_SetPanning(channel, left, right);
  assert(panning != 0);

  if (frames > 30 * 10)
      done();
}

int play() {
  int channel = Mix_PlayChannel(-1, sound, -1);
  assert(channel == 0);

  pan();

  return channel;
}

Mix_Chunk*
load(const char* filename)
{
  struct stat info;
  int result = stat(filename, &info);
  char * bytes = malloc( info.st_size );
  FILE * f = fopen( filename, "rb" );
  fread( bytes, 1, info.st_size, f  );
  fclose(f);

  SDL_RWops * ops = SDL_RWFromConstMem(bytes, info.st_size);
  Mix_Chunk * chunk = Mix_LoadWAV_RW(ops, 0);
  SDL_FreeRW(ops);
  free(bytes);

  return chunk;
}

int main(int argc, char **argv) {
  SDL_Init(SDL_INIT_AUDIO);

  int ret = Mix_OpenAudio(0, 0, 0, 0); // we ignore all these..
  assert(ret == 0);

  sound = load("the_entertainer.wav");
  assert(sound);

  int channel = play();

  emscripten_set_main_loop(pan, 30, 0);

  emscripten_run_script("element = document.createElement('input');"
                        "element.setAttribute('type', 'button');"
                        "element.setAttribute('value', 'replay!');"
                        "element.setAttribute('onclick', 'Module[\"_play\"]()');"
                        "document.body.appendChild(element);");

  printf("you should hear the sound moving from left to right. press the button to replay!\n");

  return 0;
}