Как преобразовать файл FLAC в файл wav в ios?

Я хочу создать аудиоплеер, поддерживающий формат аудиофайлов Flac. Для этого я попытался реализовать алгоритм преобразования flac в wav, который выглядит следующим образом

Помогите мне, пожалуйста.

Все время выдает ошибку

ОШИБКА: инициализация декодера: FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE

static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 x)
{
return
fputc(x, f) != EOF &&
fputc(x >> 8, f) != EOF
;
}

static FLAC__bool write_little_endian_int16(FILE *f, FLAC__int16 x)
{
return write_little_endian_uint16(f, (FLAC__uint16)x);
}

static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 x)
{
return
fputc(x, f) != EOF &&
fputc(x >> 8, f) != EOF &&
fputc(x >> 16, f) != EOF &&
fputc(x >> 24, f) != EOF
;
}

int main(int argc, char *argv[])
{
const char *input = "demo_audio_shaer.flac";
printf("aa[0]====%s",argv[0]);

FLAC__bool ok = true;
FLAC__StreamDecoder *decoder = 0;
FLAC__StreamDecoderInitStatus init_status;
FILE *fout;

if((fout = fopen(argv[2], "wb")) == NULL) {
    fprintf(stderr, "ERROR: opening %s for output\n", argv[2]);
    return 1;
}

if((decoder = FLAC__stream_decoder_new()) == NULL) {
    fprintf(stderr, "ERROR: allocating decoder\n");
    fclose(fout);
    return 1;
}

(void)FLAC__stream_decoder_set_md5_checking(decoder, true);
init_status = FLAC__stream_decoder_init_file(decoder, input, write_callback, metadata_callback, error_callback, /*client_data=*/fout);
if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
    fprintf(stderr, "ERROR: initializing decoder: %s\n", FLAC__StreamDecoderInitStatusString[init_status]);
    ok = false;
}

if(ok) {
    ok = FLAC__stream_decoder_process_until_end_of_stream(decoder);
    fprintf(stderr, "decoding: %s\n", ok? "succeeded" : "FAILED");

    fprintf(stderr, "   state: %s\n", FLAC__StreamDecoderStateString[FLAC__stream_decoder_get_state(decoder)]);
}

FLAC__stream_decoder_delete(decoder);
fclose(fout);

return 0;
}

FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const                 FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
{
FILE *f = (FILE*)client_data;
const FLAC__uint32 total_size = (FLAC__uint32)(total_samples * channels * (bps/8));
size_t i;

(void)decoder;

if(total_samples == 0) {
    fprintf(stderr, "ERROR: this example only works for FLAC files that have a total_samples count in STREAMINFO\n");
    return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
}
if(channels != 2 || bps != 16) {
    fprintf(stderr, "ERROR: this example only supports 16bit stereo streams\n");
    return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
}

/* write WAVE header before we write the first frame */
if(frame->header.number.sample_number == 0) {
    if(
       fwrite("RIFF", 1, 4, f) < 4 ||
       !write_little_endian_uint32(f, total_size + 36) ||
       fwrite("WAVEfmt ", 1, 8, f) < 8 ||
       !write_little_endian_uint32(f, 16) ||
       !write_little_endian_uint16(f, 1) ||
       !write_little_endian_uint16(f, (FLAC__uint16)channels) ||
       !write_little_endian_uint32(f, sample_rate) ||
       !write_little_endian_uint32(f, sample_rate * channels * (bps/8)) ||
       !write_little_endian_uint16(f, (FLAC__uint16)(channels * (bps/8))) || /* block align */
       !write_little_endian_uint16(f, (FLAC__uint16)bps) ||
       fwrite("data", 1, 4, f) < 4 ||
       !write_little_endian_uint32(f, total_size)
       )
    {
        fprintf(stderr, "ERROR: write error\n");
        return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
    }
}

/* write decoded PCM samples */
for(i = 0; i < frame->header.blocksize; i++) {
    if(
       !write_little_endian_int16(f, (FLAC__int16)buffer[0][i]) ||  /* left channel */
       !write_little_endian_int16(f, (FLAC__int16)buffer[1][i])     /* right channel */
       ) {
        fprintf(stderr, "ERROR: write error\n");
        return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
    }
}

return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
}

void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
{
(void)decoder, (void)client_data;

/* print some stats */
if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
    /* save for later */
    total_samples = metadata->data.stream_info.total_samples;
    sample_rate = metadata->data.stream_info.sample_rate;
    channels = metadata->data.stream_info.channels;
    bps = metadata->data.stream_info.bits_per_sample;

    fprintf(stderr, "sample rate    : %u Hz\n", sample_rate);
    fprintf(stderr, "channels       : %u\n", channels);
    fprintf(stderr, "bits per sample: %u\n", bps);
#ifdef _MSC_VER
    fprintf(stderr, "total samples  : %I64u\n", total_samples);
#else
    fprintf(stderr, "total samples  : %llu\n", total_samples);
#endif
}
}

void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
{
(void)decoder, (void)client_data;

fprintf(stderr, "Got error callback: %s\n", FLAC__StreamDecoderErrorStatusString[status]);
}

person Community    schedule 18.04.2013    source источник


Ответы (2)


Могу предложить свое решение. https://github.com/Krivoblotsky/KSAudioPlayer

Он поддерживает *.flac и многие другие форматы файлов.

person Krivoblotsky    schedule 23.05.2014
comment
основываясь на моем требовании, я интегрировал KSAudioPlayer в свой проект, и он хорошо работал для воспроизведения файла flac. Могу ли я загрузить свое приложение в магазин приложений после выполнения этой работы? - person Mak13; 10.09.2014
comment
Что вы можете. Если вы встретите Bass License, вы можете ее использовать. un4seen.com/bass.html#license - person Krivoblotsky; 10.09.2014

Невозможно воспроизвести FLAC файл напрямую с помощью AVFoundation framework. Поддерживаются:

*AAC
*HE-AAC
*AMR (Adaptive Multi-Rate, a format for speech)
*ALAC (Apple Lossless)
*iLBC (internet Low Bitrate Codec, another format for speech)
*IMA4 (IMA/ADPCM)
*linear PCM (uncompressed)
*µ-law and a-law
*MP3 (MPEG-1 audio layer 3

Но после converting до feasible format, как указано выше, это может быть played с использованием AVFoundation фреймворка.

РЕДАКТИРОВАНИЕ: Библиотека для converting to wav. Хороший пример здесь

EDIT: используйте библиотеку FFMPEG для воспроизведения FLAC.

person Paresh Navadiya    schedule 18.04.2013
comment
Я хочу воспроизвести файл FLAC в аудиоплеере. если это невозможно, то какую структуру я должен использовать для этого. - person ; 18.04.2013
comment
FLAC не поддерживается AVAudioPlayer - person Paresh Navadiya; 18.04.2013
comment
успешно преобразовал 16-битный файл flac в файл wav и воспроизвел его - person ; 26.04.2013
comment
но для 24-битного файла flac, какие изменения я должен сделать, чтобы преобразовать его в файл wav - person ; 26.04.2013