test_json.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include <math.h>
  2. #include <sekai/JSONReader.h>
  3. #include <sekai/OLABuffer.h>
  4. #include <sekai/common.h>
  5. #include <sndfile.h>
  6. void window(float *wav, int length) {
  7. int i;
  8. for (i = 0; i < length; i++) {
  9. wav[i] =
  10. wav[i] *
  11. (0.5 - 0.5 * cos(2.0 * M_PI * (float)(i + 1) / ((float)(length + 1))));
  12. }
  13. }
  14. SNDFILE *openOutFile(int samplerate) {
  15. SF_INFO info;
  16. memset(&info, 0, sizeof(info));
  17. info.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;
  18. info.samplerate = samplerate;
  19. info.channels = 1;
  20. return sf_open("output.wav", SFM_WRITE, &info);
  21. }
  22. int main() {
  23. JSONReader json;
  24. json.readFile("test.json");
  25. OLABuffer ola(16 * 1024);
  26. float currentTime = 0;
  27. float currentIndex = 0;
  28. int samplerate = json.getSamplerate();
  29. printf("samplerate %i\n", samplerate);
  30. float f0 = json.getPitch();
  31. int T0 = (int)((samplerate / f0) + 0.5);
  32. printf("f0 %f\n", f0);
  33. float new_f0 = 440;
  34. int new_T0 = (int)((samplerate / new_f0) + 0.5);
  35. float y_end = json.getLength();
  36. float *buffer = new float[T0 * 2];
  37. float *buffera = new float[T0 * 2];
  38. float *bufferb = new float[T0 * 2];
  39. int outbuf_len = 1024;
  40. float *outbuf = new float[outbuf_len];
  41. float x[2] = {0, 10.0};
  42. float y[2] = {0, y_end};
  43. int n = 2;
  44. float x_end = x[n - 1];
  45. SNDFILE *sf = openOutFile(samplerate);
  46. while (currentTime < x_end) {
  47. currentIndex = ola.currentTime(); // rename to currentIndex
  48. currentTime = currentIndex / samplerate;
  49. if (currentTime >= x_end) break;
  50. float pos = interp_linear(x, y, n, currentTime);
  51. memset(bufferb, 0, sizeof(float) * T0 * 2);
  52. memset(buffera, 0, sizeof(float) * T0 * 2);
  53. float interp;
  54. bool result = json.copyIn(buffera, bufferb, &interp, T0 * 2, pos);
  55. for (int i = 0; i < T0 * 2; i++) {
  56. buffer[i] = buffera[i] * (1 - interp) + bufferb[i] * interp;
  57. }
  58. window(buffer, T0 * 2);
  59. ola.ola(buffer, T0 * 2, new_T0);
  60. while (ola.isFilled(outbuf_len * 4)) {
  61. ola.pop(outbuf, outbuf_len);
  62. sf_write_float(sf, outbuf, outbuf_len);
  63. }
  64. }
  65. sf_close(sf);
  66. }