Skip to content

Instantly share code, notes, and snippets.

@fukuroder
Last active August 29, 2015 14:05
Show Gist options
  • Save fukuroder/5b046dc2273f8a67a1f1 to your computer and use it in GitHub Desktop.
Save fukuroder/5b046dc2273f8a67a1f1 to your computer and use it in GitHub Desktop.
Raspberry PiでFLACファイル再生するテスト
/*
* alsa_flac_test.cpp
*
* Created by fukuroda (https://github.com/fukuroder)
*/
// g++ alsa_flac_test.cpp -std=c++0x -O3 -lasound -lsndfile
#include<alsa/asoundlib.h> // sudo apt-get install libasound2-dev
#include<sndfile.h> // sudo apt-get install libsndfile1-dev
#include<iostream>
#include<vector>
#include<stdexcept>
int main()
{
const char* device = "hw:ALSA"; // PWM
SNDFILE *sf = nullptr;
snd_pcm_t *pcm = nullptr;
try
{
// open sound file
SF_INFO info = { 0 };
sf = ::sf_open("kmb.flac", SFM_READ, &info);
if( sf == nullptr )
{
throw std::runtime_error("sf_open error");
}
// open audio device
if( ::snd_pcm_open(
&pcm,
device,
SND_PCM_STREAM_PLAYBACK,
0) )
{
throw std::runtime_error("snd_pcm_open error");
}
// set parameters
if( ::snd_pcm_set_params(
pcm,
SND_PCM_FORMAT_S16,
SND_PCM_ACCESS_RW_INTERLEAVED,
2,
44100,
0,
100*1000) ) // 100ms
{
throw std::runtime_error("snd_pcm_set_params error");
}
// get buffer size and period size
snd_pcm_uframes_t buffer_size = 0;
snd_pcm_uframes_t period_size = 0;
if( ::snd_pcm_get_params(
pcm,
&buffer_size,
&period_size) )
{
throw std::runtime_error("snd_pcm_get_params error");
}
// allocate buffer
std::vector<short> buffer(2*period_size);
std::cout << "start ("
<< "buffer_size=" << buffer_size << ", "
<< "period_size=" << period_size << ")"
<< std::endl;
sf_count_t read_count = 0;
do{
// read
read_count = ::sf_readf_short(sf, buffer.data(), period_size);
// write
if( ::snd_pcm_writei(pcm, buffer.data(), read_count) < 0 )
{
throw std::runtime_error("snd_pcm_writei error");
}
}while(read_count == period_size);
std::cout << "end" << std::endl;
}
catch(std::exception &ex)
{
std::cout << "error:" << ex.what() << std::endl;
}
if(pcm != nullptr)
{
// close audio device
::snd_pcm_close(pcm);
}
if(sf != nullptr)
{
// close sound file
::sf_close(sf);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment