#include "Tools.h"
#include "WAVFormat.h"
#include <stdio.h>
#include <fcntl.h>
#include <linux/soundcard.h>
struct WAV_HEADER mWaveHeader;
int music_fd;
void parse(const char *pWaveFile, struct WAV_HEADER *pHeader) {
if((music_fd = open(pWaveFile, O_RDONLY)) == -1)
error("cannot open file: %s", pWaveFile);
if(read(music_fd, pHeader, 20) <= 0)
error("error reading file: %s", pWaveFile);
if(read(music_fd, &pHeader->nEncodeTag, pHeader->nFormatSize) <= 0)
error("error reading format chunk");
if(read(music_fd, &pHeader->cDataHeader, 8) <= 0)
error("error reading data chunk");
if(pHeader->cDataHeader[0] != 'd') {
printf("skip factory chunk\n");
if(lseek(music_fd, pHeader->nDataBytes, SEEK_CUR) == -1)
error("error skipping factor chunk");
if(read(music_fd, &pHeader->cDataHeader, 8) <= 0)
error("error re-read data chunk");
}
}
void print(struct WAV_HEADER *p) {
printChars("riff header: ", p->cRiffHeader, 4);
printf("riff size: %d\n", p->nRiffSize);
printChars("riff type: ", p->cRiffTypeID, 4);
printChars("format header: ", p->cFormatHeader, 4);
printf("format chunk size: %d\n", p->nFormatSize);
printf("format encode tag: %d\n", p->nEncodeTag);
printf("channels: %d\n", p->nChannels);
printf("sample rate: %dHz\n", p->nSampleRate);
printf("bytes per sec: %d bytes\n", p->nBytesPerSec);
printf("block align: %d bytes\n", p->nBlockAlign);
printf("bits per sample: %d bits\n", p->nBitsPerSample);
printChars("data header: ", p->cDataHeader, 4);
printf("data chunk size: %d\n\n", p->nDataBytes);
}
void playback(struct WAV_HEADER *pHeader) {
int fd;
int stereo, sampleFormat, sampleRate;
char buf[1024];
int num_read = 1024, num_write = 1024, offset = 0;
if((fd = open("/dev/dsp", O_WRONLY)) == -1)
error("cannot open audio device");
stereo = pHeader->nChannels > 1;
if(ioctl(fd, SNDCTL_DSP_STEREO, &stereo) == -1)
error("sound card do not support stereo");
sampleFormat = AFMT_S16_LE;
if(pHeader->nBitsPerSample == 8)
sampleFormat = AFMT_U8;
if(ioctl(fd, SNDCTL_DSP_SETFMT, &sampleFormat) == -1)
error("error set audio format");
sampleRate = pHeader->nSampleRate;
if(ioctl(fd, SNDCTL_DSP_SPEED, &sampleRate) == -1)
error("error set sample rate");
printf("playback started...\n");
if(pHeader->nBitsPerSample == 24) {
num_read = 3; num_write = 2; offset = 1;
}
while(read(music_fd, buf, num_read) > 0)
if(write(fd, buf+offset, num_write) == -1)
error("error writing dsp device file");
printf("Playback finished.\n");
}
void play(const char *pWaveFile) {
parse(pWaveFile, &mWaveHeader);
print(&mWaveHeader);
playback(&mWaveHeader);
}
- 1
- 2
- 3
- 4
- 5
- 6
前往页