LoginSignup
1

More than 5 years have passed since last update.

raspberry pi 1でtensorflow lite その14

Posted at

概要

raspberry pi 1でtensorflow liteやってみた。
マイク入力を扱うので、alsaを叩いてみた。

写真

CIMG2821.JPG

Makefileを書く。

.PHONY: all clean

all: main

main: pcm4.c
    gcc pcm4.c -o test -lasound -lm
clean:
    rm -f test


サンプルコード

マイク入力をそのまま、スピーカー出力。

#include <stdio.h>
#include <alsa/asoundlib.h>

#define OUT_FREQ            44100
#define IN_FREQ             44100
int main(int argc, char * argv[])
{
    int err;
    int i;
    snd_pcm_t * in_handle;
    snd_pcm_t * out_handle;
    snd_pcm_sframes_t frames;
    char * device = "default";
    short in_buffer[IN_FREQ * 5];
    short out_buffer[OUT_FREQ * 5];
    if ((err = snd_pcm_open(&in_handle, device, SND_PCM_STREAM_CAPTURE, 0)) < 0)
    {
        fprintf (stderr, "Capture open error: %s\n", snd_strerror(err));
        return 1;
    }
    if ((err = snd_pcm_set_params(in_handle, SND_PCM_FORMAT_S16_LE, SND_PCM_ACCESS_RW_INTERLEAVED, 1, IN_FREQ, 1, 1000 * 1000)) < 0)
    {
        fprintf (stderr, "Capture open error: %s\n", snd_strerror(err));
        return 1;
    }
    if ((err = snd_pcm_open(&out_handle, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0)
    {
        fprintf (stderr, "Playback open error: %s\n", snd_strerror(err));
        return 1;
    }
    if ((err = snd_pcm_set_params(out_handle, SND_PCM_FORMAT_S16_LE, SND_PCM_ACCESS_RW_INTERLEAVED, 2, OUT_FREQ, 1, 1500 * 1000)) < 0)
    {
        fprintf (stderr, "Playback open error: %s\n", snd_strerror(err));
        return 1;
    }
    while(1)
    {
        frames = snd_pcm_readi(in_handle, in_buffer, IN_FREQ);
        if (frames < 0)
        {
            frames = snd_pcm_recover(in_handle, frames, 0);
        }
        if (frames < 0)
        {
            fprintf (stderr, "snd_pcm_readi failed: %s\n", snd_strerror(frames));
        }
        fprintf(stderr, "%d  ", frames);
        for (i = 0; i < frames; i++)
        {
            out_buffer[2 * i] = in_buffer[i];
            out_buffer[2 * i + 1] = in_buffer[i];
        }
        frames = snd_pcm_writei(out_handle, out_buffer, OUT_FREQ);
        if (frames < 0)
        {
            frames = snd_pcm_recover(out_handle, frames, 0);
        }
        if (frames < 0)
        {
            fprintf(stderr, "snd_pcm_writei failed: %s\n", snd_strerror(frames));
        }
    }
    snd_pcm_close(in_handle);
    snd_pcm_close(out_handle);
    return 0;
}



以上。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1