1
0

player_oss.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // minimp3 example player application for Linux/OSS
  2. // this file is public domain -- do with it whatever you want!
  3. #include "libc.h"
  4. #include "minimp3.h"
  5. #include <unistd.h>
  6. #include <fcntl.h>
  7. #include <sys/mman.h>
  8. #include <sys/types.h>
  9. #include <sys/stat.h>
  10. #include <sys/ioctl.h>
  11. #include <linux/soundcard.h>
  12. size_t strlen(const char *s);
  13. #define out(text) write(1, (const void *) text, strlen(text))
  14. int main(int argc, char *argv[]) {
  15. mp3_decoder_t mp3;
  16. mp3_info_t info;
  17. int fd, pcm;
  18. void *file_data;
  19. unsigned char *stream_pos;
  20. signed short sample_buf[MP3_MAX_SAMPLES_PER_FRAME];
  21. int bytes_left;
  22. int frame_size;
  23. int value;
  24. out("minimp3 -- a small MPEG-1 Audio Layer III player based on ffmpeg\n\n");
  25. if (argc < 2) {
  26. out("Error: no input file specified!\n");
  27. return 1;
  28. }
  29. fd = open(argv[1], O_RDONLY);
  30. if (fd < 0) {
  31. out("Error: cannot open `");
  32. out(argv[1]);
  33. out("'!\n");
  34. return 1;
  35. }
  36. bytes_left = lseek(fd, 0, SEEK_END);
  37. file_data = mmap(0, bytes_left, PROT_READ, MAP_PRIVATE, fd, 0);
  38. stream_pos = (unsigned char *) file_data;
  39. bytes_left -= 100;
  40. out("Now Playing: ");
  41. out(argv[1]);
  42. mp3 = mp3_create();
  43. frame_size = mp3_decode(mp3, stream_pos, bytes_left, sample_buf, &info);
  44. if (!frame_size) {
  45. out("\nError: not a valid MP3 audio file!\n");
  46. return 1;
  47. }
  48. #define FAIL(msg) { \
  49. out("\nError: " msg "\n"); \
  50. return 1; \
  51. }
  52. pcm = open("/dev/dsp", O_WRONLY);
  53. if (pcm < 0) FAIL("cannot open DSP");
  54. value = AFMT_S16_LE;
  55. if (ioctl(pcm, SNDCTL_DSP_SETFMT, &value) < 0)
  56. FAIL("cannot set audio format");
  57. if (ioctl(pcm, SNDCTL_DSP_CHANNELS, &info.channels) < 0)
  58. FAIL("cannot set audio channels");
  59. if (ioctl(pcm, SNDCTL_DSP_SPEED, &info.sample_rate) < 0)
  60. FAIL("cannot set audio sample rate");
  61. out("\n\nPress Ctrl+C to stop playback.\n");
  62. while ((bytes_left >= 0) && (frame_size > 0)) {
  63. stream_pos += frame_size;
  64. bytes_left -= frame_size;
  65. write(pcm, (const void *) sample_buf, info.audio_bytes);
  66. frame_size = mp3_decode(mp3, stream_pos, bytes_left, sample_buf, NULL);
  67. }
  68. close(pcm);
  69. return 0;
  70. }