EzDevInfo.com

flac.js

FLAC decoder in JavaScript FLAC — Audiocogs

ffmpeg to convert from flac to wav

I need to convert a flac file to a wav file without changing sample rate and bit depth. As far as I know changing these properties may distort the audio, so how do i specify them not to be changed?

Also, is there any way to prevent metadata to be written to the output file?


Source: (StackOverflow)

How to build Flac for BlackBerry Cascade?

I want to build Flac for a project I'm working on in Cascades on a Mac in Mometics.

http://sourceforge.net/projects/flac/files/flac-src/

I have in the past successfully built LAME and Ogg by just dragging the c and h files into my Workspace src folder before but that's not working with Flac. I have no idea about using make files, config, building libraries, etc.

Does anyone know how I can build Flac so that I can use it in my project?

I'm on a Mac 10.8.3, want to use Flac 1.2.1, Mometics Version: 10.1.0 Build id: v201303191709 10


Source: (StackOverflow)

Advertisements

Convert WAV to FLAC with libFLAC in C#

I've tried to port the libFLAC encoding example to C# and came up with this code:

public class LibFLAC {

    public static void Test() {
        string inputPath = Path.Combine("D:\\", "_", "test.pcm");
        string outputPath = Path.Combine("D:\\", "_", "test.flac");

        uint channels = 2;
        uint bitsPerSample = 16;
        uint sampleRate = 44100;


        IntPtr encoder = FLAC__stream_encoder_new();
        if (encoder == IntPtr.Zero) throw new Exception("Encoder: NEW failed");

        bool ok = true;
        ok &= FLAC__stream_encoder_set_channels(encoder, channels);
        ok &= FLAC__stream_encoder_set_bits_per_sample(encoder, bitsPerSample);
        ok &= FLAC__stream_encoder_set_sample_rate(encoder, sampleRate);
        ok &= FLAC__stream_encoder_set_compression_level(encoder, 5);
        // ok &= FLAC__stream_encoder_set_verify(encoder, true);
        if (!ok) throw new Exception("Encoder: SET failed");

        int status = FLAC__stream_encoder_init_file(encoder, outputPath, IntPtr.Zero, IntPtr.Zero);
        if (status != 0) throw new Exception("Encoder: INIT FILE failed");


        using (FileStream stream = new FileStream(inputPath, FileMode.Open, FileAccess.Read)) {
            uint bps = bitsPerSample / 8;
            byte[] buffer = new byte[channels * bps * 1024];
            Int32[] pcm = new Int32[channels * 1024];
            int read;

            while ((read = stream.Read(buffer, 0, buffer.Length)) != 0) {
                for (var i = 0; i < read / bps; i++) {
                    pcm[i] = (Int32) (((uint) buffer[i * 2 + 1] << 8) | (uint) buffer[i * 2]);
                }

                ok = FLAC__stream_encoder_process_interleaved(encoder, pcm, (uint) (read / bps / channels));
                if (!ok) throw new Exception("Encoder: PROCESS INTERLEAVED failed ::: " + FLAC__stream_encoder_get_state(encoder) + " ::: " + FLAC__stream_encoder_get_verify_decoder_state(encoder));
            }

            ok = FLAC__stream_encoder_finish(encoder);
            if (!ok) throw new Exception("Encoder: FINISH failed");

            FLAC__stream_encoder_delete(encoder);
            encoder = IntPtr.Zero;
        }



        Console.WriteLine("\n\n\nDone");
        Console.ReadKey();
    }


    [DllImport("libFLAC", CallingConvention = CallingConvention.Cdecl)]
    public static extern IntPtr FLAC__stream_encoder_new();

    [DllImport("libFLAC", CallingConvention = CallingConvention.Cdecl)]
    public static extern void FLAC__stream_encoder_delete(IntPtr encoder);


    [DllImport("libFLAC", CallingConvention=CallingConvention.Cdecl)]
    public static extern bool FLAC__stream_encoder_set_verify(IntPtr encoder, bool value);

    [DllImport("libFLAC", CallingConvention = CallingConvention.Cdecl)]
    public static extern bool FLAC__stream_encoder_set_channels(IntPtr encoder, uint value);

    [DllImport("libFLAC", CallingConvention = CallingConvention.Cdecl)]
    public static extern bool FLAC__stream_encoder_set_bits_per_sample(IntPtr encoder, uint value);

    [DllImport("libFLAC", CallingConvention = CallingConvention.Cdecl)]
    public static extern bool FLAC__stream_encoder_set_sample_rate(IntPtr encoder, uint value);

    [DllImport("libFLAC", CallingConvention = CallingConvention.Cdecl)]
    public static extern bool FLAC__stream_encoder_set_compression_level(IntPtr encoder, uint value);


    [DllImport("libFLAC", CallingConvention = CallingConvention.Cdecl)]
    public static extern int FLAC__stream_encoder_init_file(IntPtr encoder, string filename, IntPtr progress_callback, IntPtr client_data);

    [DllImport("libFLAC", CallingConvention = CallingConvention.Cdecl)]
    public static extern bool FLAC__stream_encoder_process_interleaved(IntPtr encoder, Int32[] buffer, uint samples);

    [DllImport("libFLAC", CallingConvention = CallingConvention.Cdecl)]
    public static extern bool FLAC__stream_encoder_finish(IntPtr encoder);


    [DllImport("libFLAC", CallingConvention = CallingConvention.Cdecl)]
    public static extern int FLAC__stream_encoder_get_state(IntPtr encoder);

    [DllImport("libFLAC", CallingConvention = CallingConvention.Cdecl)]
    public static extern int FLAC__stream_encoder_get_verify_decoder_state(IntPtr encoder);

}

The test.pcm file is raw PCM data without WAV or RIFF headers and in the given format (2 channels, 16 bps and 44.1 kHz).

The code works and the FLAC plays normaly, but the created file is almost as big as the source wav (WAV: 47MB --> FLAC: 45MB) and there are 200ms noise at the end. If I send it through the FLAC Frontend GUI with the same settings I get a 35MB file, so the WAV should be OK.

Also, if I enable FLAC__stream_encoder_set_verify, the program immediately fails at FLAC__stream_encoder_process_interleaved with

  • FLAC__StreamEncoderState = 4 (VERIFY_MISMATCH_IN_AUDIO_DATA - The verify decoder detected a mismatch between the original audio signal and the decoded audio signal.) and
  • FLAC__StreamDecoderState = 3 (READ_FRAME - The decoder is ready to or is in the process of reading a frame.)

which makes no sense?

Did I missed something or made a mistake in the conversion?


Source: (StackOverflow)

Convert raw PCM to FLAC?

EDIT: I've updated the code below to resemble the progress I have made. I'm trying to write the .wav header myself. The code does not work properly as of now, the audio is not being written to the file properly. The code does not contain any attempts to convert it to a .flac file yet.


I am using a Raspberry Pi (Debian Linux) to record audio with the ALSA library. The recording works fine, but I need to encode the input audio into the FLAC codec.

This is where I get lost. I have spent a considerable amount of time trying to figure out how to convert this raw data into FLAC, but I keep coming up with examples of how to convert .wav files into .flac files.

Here is the current (updated) code I have for recording audio with ALSA (it may be a bit rough, I'm still picking up C++):

// Use the newer ALSA API
#define ALSA_PCM_NEW_HW_PARAMS_API

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

struct Riff
{
  char chunkId[4]; // "RIFF" (assuming char is 8 bits)
  int chunkSize; // (assuming int is 32 bits)
  char format[4]; // "WAVE"
};

struct Format
{
  char chunkId[4]; // "fmt "
  int chunkSize;
  short format; // assuming short is 16 bits
  short numChannels;
  int sampleRate;
  int byteRate;
  short align;
  short bitsPerSample;
};

struct Data
{
  char chunkId[4]; // "data"
  int chunkSize; // length of data
  char* data;
};

struct Wave // Actual structure of a PCM WAVE file
{
  Riff riffHeader;
  Format formatHeader;
  Data dataHeader;
};

int main(int argc, char *argv[])
{
        void saveWaveFile(struct Wave *waveFile);

        long loops;
        int rc;
        int size;
        snd_pcm_t *handle;
        snd_pcm_hw_params_t *params;
        unsigned int sampleRate = 44100;
        int dir;
        snd_pcm_uframes_t frames;
        char *buffer;
        char *device = (char*) "plughw:1,0";
        //char *device = (char*) "default";

        printf("Capture device is %s\n", device);
        /* Open PCM device for recording (capture). */
        rc = snd_pcm_open(&handle, device, SND_PCM_STREAM_CAPTURE, 0);
        if (rc < 0)
        {
                fprintf(stderr, "Unable to open PCM device: %s\n", snd_strerror(rc));
                exit(1);
        }

        /* Allocate a hardware parameters object. */
        snd_pcm_hw_params_alloca(&params);

        /* Fill it in with default values. */
        snd_pcm_hw_params_any(handle, params);

        /* Set the desired hardware parameters. */

        /* Interleaved mode */
        snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);

        /* Signed 16-bit little-endian format */
        snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE);

        /* Two channels (stereo) */
        snd_pcm_hw_params_set_channels(handle, params, 2);

        /* 44100 bits/second sampling rate (CD quality) */
        snd_pcm_hw_params_set_rate_near(handle, params, &sampleRate, &dir);

        /* Set period size to 32 frames. */
        frames = 32;
        snd_pcm_hw_params_set_period_size_near(handle, params, &frames, &dir);

        /* Write the parameters to the driver */
        rc = snd_pcm_hw_params(handle, params);
        if (rc < 0)
        {
                fprintf(stderr, "Unable to set HW parameters: %s\n", snd_strerror(rc));
                exit(1);
        }

        /* Use a buffer large enough to hold one period */
        snd_pcm_hw_params_get_period_size(params, &frames, &dir);
        size = frames * 4; /* 2 bytes/sample, 2 channels */
        buffer = (char *) malloc(size);

        /* We want to loop for 5 seconds */
        snd_pcm_hw_params_get_period_time(params, &sampleRate, &dir);
        loops = 5000000 / sampleRate;

        while (loops > 0)
        {
                loops--;
                rc = snd_pcm_readi(handle, buffer, frames);
                if (rc == -EPIPE)
                {
                        /* EPIPE means overrun */
                        fprintf(stderr, "Overrun occurred.\n");
                        snd_pcm_prepare(handle);
                } else if (rc < 0)
                {
                        fprintf(stderr, "Error from read: %s\n", snd_strerror(rc));
                } else if (rc != (int)frames)
                {
                        fprintf(stderr, "Short read, read %d frames.\n", rc);
                }
                if (rc != size) fprintf(stderr, "Short write: wrote %d bytes.\n", rc);
        }

        Wave wave;

        strcpy(wave.riffHeader.chunkId, "RIFF");
        wave.riffHeader.chunkSize = 36 + size;
        strcpy(wave.riffHeader.format, "WAVE");

        strcpy(wave.formatHeader.chunkId, "fmt");
        wave.formatHeader.chunkSize = 16;
        wave.formatHeader.format = 1; // PCM, other value indicates compression
        wave.formatHeader.numChannels = 2; // Stereo
        wave.formatHeader.sampleRate = sampleRate;
        wave.formatHeader.byteRate = sampleRate * 2 * 2;
        wave.formatHeader.align = 2 * 2;
        wave.formatHeader.bitsPerSample = 16;

        strcpy(wave.dataHeader.chunkId, "data");
        wave.dataHeader.chunkSize = size;
        wave.dataHeader.data = buffer;

        saveWaveFile(&wave);

        snd_pcm_drain(handle);
        snd_pcm_close(handle);
        free(buffer);

        return 0;
}

void saveWaveFile(struct Wave *waveFile)
{
        FILE *file = fopen("test.wav", "wb");
        size_t written;

        if (file == NULL)
        {
                fprintf(stderr, "Cannot open file for writing.\n");
                exit(1);
        }

        written = fwrite(waveFile, sizeof waveFile[0], 1, file);
        fclose(file);

        if (written < 1);
        {
                fprintf(stderr, "Writing to file failed, error %d.\n", written);
                exit(1);
        }
}

How would I go about converting the PCM data into the FLAC and save it to disk for later use? I have downloaded libflac-dev already and just need an example to go off of.


The way I am doing it right now:

./capture > test.raw     // or   ./capture > test.flac

The way it should be (program does everything for me):

./capture

Source: (StackOverflow)

ruby - IO.popen not working lame stdin and stdout encoding

I've been working with pipes and IO.popen specifically in Ruby and have come across a problem that I can't figure out. I am trying to write binary data from the flac process to the lame process into a file. The code structure I am using is below.

# file paths
file = Pathname.new('example.flac').realpath
dest = Pathname.new('example.mp3')

# execute the process and return the IO object
wav = IO.popen("flac --decode --stdout \"#{file}\"", 'rb')
lame = IO.popen("lame -V0 --vbr-new - -", 'r+b')

# write output from wav to the lame IO object
lame << wav.read

# close pipe for writing (should indicate to the
# process that input for stdin is finished).
lame.close_write

# open up destiniation file and write from lame stdout
dest.open('wb'){|out|
    out << lame.read
}

# close all pipes
wav.close
lame.close

However, it doesn't work. After flac has run, the script hangs and lame remains idle (no processor usage at all). No errors or exceptions occur.

I am using cygwin on Windows 7, with the cygwin ruby package (1.9.3p429 (2013-05-15) [i386-cygwin]).

I must be doing something wrong, any help is much appreciated. Thanks!

EXTRA #1

I am wanting to pipe in and out the binary data from the lame process because I am trying to create a platform independent (ruby support limited of course) to transcode audio files, and the Windows binary of lame only supports Windows' path names, and not cygwin's.

EDIT #1

I read in some places (I did not save the URLs, I'll try looking for them in my browser history) that IO.popen has known issues with blocking processes in Windows and that this could be the case.

I have played around with other libraries including Ruby's Open3.popen3 and Open4, however following a very similar code structure to the one above, the lame process still hangs and remains unresponsive.

EDIT #2

I found this article which talked about the limitations of of Windows's cmd.exe and how it prevents the use of streamed data from files to stdin.

I refactored my code to look like shown below to test this out, and as it turns out, lame freezes on stdin write. If I removed (comment out) that line, the lame process executes (with an 'unsupported audio format' warning). Perhaps what the article said could explain my problem here.

# file paths
file = Pathname.new('example.flac').realpath
dest = Pathname.new('example.mp3')

# some local variables
read_wav = nil
read_lame = nil

# the flac process, which exits succesfully
IO.popen("flac --decode --stdout \"#{file}\"", 'rb'){|wav|
    until wav.eof do
        read_wav = wav.read
    end
}

# the lame process, which fails
IO.popen("lame -V0 --vbr-new --verbose - -", 'r+b'){|lame|
    lame << read_wav # if I comment out this, the process exits, instead of hanging
    lame.close_write
    until lame.eof do
        read_lame << lame.read
    end
}

EDIT #3

I found this stackoverflow which (in the first answer) mentioned that cygwin pipe implementation is unreliable. This could perhaps not actually be related to Windows (at least not directly) but instead to cygwin and its emulation. I have instead opted to use the following code, based upon icy's answer, which works!

flac = "flac --decode --stdout \"#{file}\""
lame = "lame -V0 --vbr-new --verbose - \"#{dest}\""

system(flac + ' | ' + lame)

Source: (StackOverflow)

How accurate is mutagen track length info

I'm doing some auditing of my music library (using Mutagen/Python), including looking for duplicates. In particular, I am writing a program to look for duplicates and I am using track-length as part of the way I compare two tracks. In the process of doing that, I'm finding some small discrepancies (say 2 seconds) between the track length of the mp3 version versus the m4a version.

Is this "real" (i.e., the different encoding distorts the track length - yikes!) or is this something to do with how the tags are created or how they are read?

If the difference is real and unavoidable, what comparison tolerance should I be setting for equality?


Source: (StackOverflow)

Linux script to transfer (ID3) tags from FLAC to MP3

For my media server, I am looking for ways to transfer tags from my FLAC files to MP3.

In a bash script, I can extract tags using metaflac to local vars, but when tagging mp3 with id3v2, I seem to loose national characters (guess it must be unicode?)

Also I need to be able to set replay gain tags, and album art (all present in the FLAC's).

I am looking for a scripted solution to run unattended.

TIA Roadrunner


Source: (StackOverflow)

how to install flac support (flac libraries) to sox in Windows

when I try to work on flac files I got

"no handler for file extension flac"

error. is there any way to solve this problem in windows.


Source: (StackOverflow)

How to convert FLAC file to wav file in ios?

I want to create a audio player that support Flac format of audio files.For this i tried to implement the algorithm of flac to wav conversion which is as follow

Please help me.

All time it gives me error

ERROR: initializing decoder: 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]);
}

Source: (StackOverflow)

Can't play ogg and flac

Qt 5.0.1 QMediaPlayer on 32 bit Windows XP can only play MP3 and WAV files. How can I extend it to play OGG and FLAC files too?


Source: (StackOverflow)

Detect if file is MP3

I'm writing a C++ library for decoding and encoding audio between different formats/codecs. I have a routine for quickly detecting the format before loading the required codec library.

For WAV files one can simple look for the ASCII values "RIFF" and "WAVE" at the start of the file. The same applies to FLAC, we can simply read in the first 4 bytes, which will be "fLaC".

But how can I quickly detect if a file is MP3? I can't rely on the file extension. I also can't try to decode the first MP3 frame, since there might be additional data at the start of the file (eg: ID3, cover image, etc).


Source: (StackOverflow)

How to convert the WAV/OGG file to FLAC file in Android?

I can only find that ICS 4.0 support decoding of FLAC, but encode. I need some encoder to convert wav to flac, but currenty I can't find it. I find there is a jFlac avaible , but I don't know how to use this library, just simply convert the files.

Could anyone give me a hand on it?

Today, I just some idea by myself, with using the JavaFlacEncoder. and it works for certain bitrates of WAV.

I changed the value into a hard coding value in which it is working now.

/*
 * Copyright (C) 2010  Preston Lacey http://javaflacencoder.sourceforge.net/
 * All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

package javaFlacEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.io.IOException;
/**
 * FLAC_FileEncoder is a class to encode an input wav File to an output Flac
 * file. It allows the EncodingConfiguration to be set only once, prior to
 * encoding the entire File.
 * 
 * @author Preston Lacey
 * @author Bo Tan (Temple)
 */
public class FLAC_FileEncoder {
    /** Maximum number of bytes to read from file at once */
    private static final int MAX_READ = 16384;

    /** Status enum for encode result */
    public enum Status {
        /** Unknown State. */
        UNKNOWN,
        /** Everything went well */
        FULL_ENCODE,

        /** Something unspecified went wrong...*/
        GENERAL_ERROR,

        /** internal error is something that went haywire that was discovered
         * due to internal sanity checks. A problem in API. */
        INTERNAL_ERROR,

        /** File given was not able to be read */
        UNSUPPORTED_FILE,

        /** Generic file IO Error */
        FILE_IO_ERROR,

        /** Sample size unsupported */
        UNSUPPORTED_SAMPLE_SIZE,

        /** Error with output file */
        OUTPUT_FILE_ERROR,
        /** No errors found. */
        OK
    }
    FLACEncoder flac = null;
    StreamConfiguration sc = null;
    EncodingConfiguration ec = null;
    File outFile = null;
    int lastTotalSamples = 0;
    boolean useThreads;

    /**
     * Constructor creates a FLAC_FileEncoder object with default
     * StreamConfiguration configuration and default EncodingConfiguration.
     * Thread use defaults to true.
     */
    public FLAC_FileEncoder() {
        flac = new FLACEncoder();
        sc = new StreamConfiguration();
        ec = new EncodingConfiguration();
        useThreads = true;
    }

    /**
     * Specify whether to use multiple threads or not.
     * @param val true to use threads, false otherwise.
     */
    public void useThreads(boolean val) {
        useThreads = val;
    }

    private void adjustConfigurations(){//(AudioFormat format) {
        int sampleRate = 16000;//(int)format.getSampleRate();
        int sampleSize = 16; //(int)format.getSampleSizeInBits();
        int channels =1;// (int)format.getChannels();
        //int blockSize = sc.getMaxBlockSize();
        /*sc = new StreamConfiguration(channels, blockSize, blockSize,
                sampleRate, sampleSize);*/
        sc.setSampleRate(sampleRate);
        sc.setBitsPerSample(sampleSize);
        sc.setChannelCount(channels);
    }

    /**
     * Set the stream configuration for this encoder to use. Note that the audio
     * characteristics(number of channels, sample rate, and sample size), will
     * be set to match the input file at encode time, so needn't be set in the
     * given StreamConfiguration object.
     * 
     * @param config StreamConfiguration to use for encoding.
     */
    public void setStreamConfig(StreamConfiguration config) {sc = config; }

    /**
     * Set the EncodingConfiguration to use for encoding.
     * @param config EncodingConfiguration to use.
     */
    public void setEncodingConfig(EncodingConfiguration config){ec = config;}

    private Status openStream() {
        Status status = Status.OK;
        boolean result = flac.setStreamConfiguration(sc);
        result = result & flac.setEncodingConfiguration(ec);
        if( !result)
            status = Status.INTERNAL_ERROR;
        else {
            FLACFileOutputStream fout = null;
            try {
               fout = new FLACFileOutputStream(outFile.getPath());
            } catch(IOException e) {
               status = Status.OUTPUT_FILE_ERROR;
               e.printStackTrace();
            }
            if( status == Status.OK) {
                flac.setOutputStream(fout);
                try {
                    flac.openFLACStream();
                }catch(IOException e) {
                    status = Status.INTERNAL_ERROR;
                }
            }
            else
                status = Status.OUTPUT_FILE_ERROR;
        }
        return status;
    }

    /**
     * Encode the given input wav file to an output file.
     *
     * @param inputFile Input wav file to encode.
     * @param outputFile Output file to write FLAC stream to. If file exists, it
     * will be overwritten without prompting.
     *
     * @return Status flag for encode
     */
    public Status encode(File inputFile, File outputFile) {
        Status status = Status.FULL_ENCODE;
        this.outFile = outputFile;
        //take file and initial configuration.
        //open file
//        AudioInputStream sin = null;
//        AudioFormat format = null;
//        //File inputFile = new File("encoderTest.wav");
//        try {
//            sin = AudioSystem.getAudioInputStream(inputFile);
//        }catch(IOException e) {
//            status = Status.FILE_IO_ERROR;
//        }catch (UnsupportedAudioFileException e) {
//            status = Status.UNSUPPORTED_FILE;
//        }finally {
//            if(status != Status.FULL_ENCODE)
//                return status;
//        }


        FileInputStream sin=null;
        try {
            sin = new FileInputStream(inputFile);
        } catch (FileNotFoundException e1) {
            status = Status.FILE_IO_ERROR;
            e1.printStackTrace();
        }finally {
            if (status != Status.FULL_ENCODE)
                return status;
        }



        try {
//            format = sin.getFormat();
            //sanitize and optimize configurations
             adjustConfigurations();  //adjustConfigurations(format);
            //open stream
            openStream();
            int frameSize = 2;//format.getFrameSize();
            int sampleSize = 16;//format.getSampleSizeInBits();
            int bytesPerSample = sampleSize/8;
            if(sampleSize %8 != 0) {
                //end processing now
                Exception newEx = new Exception(Status.UNSUPPORTED_SAMPLE_SIZE.name());
                throw newEx;

            }
            int channels =1;// format.getChannels();
            boolean bigEndian =false;// format.isBigEndian();
            byte[] samplesIn = new byte[(int)MAX_READ];
            int samplesRead;
            int framesRead;
            int[] sampleData = new int[MAX_READ*channels/frameSize];
            int blockSize = sc.getMaxBlockSize();
            int unencodedSamples = 0;
            int totalSamples = 0;
            while((samplesRead = sin.read(samplesIn, 0, MAX_READ)) != -1) {
                //System.err.println("Read: " + read);
                framesRead = samplesRead/(frameSize);
                if(bigEndian) {
                    for(int i = 0; i < framesRead*channels; i++) {
                        int lower8Mask = 255;
                        int temp = 0;
                        int totalTemp = 0;
                        for(int x = bytesPerSample-1; x >= 0; x++) {
                            int upShift = 8*x;
                            if(x == 0)//don't mask...we want sign
                                temp = ((samplesIn[bytesPerSample*i+x]) << upShift);
                            else
                                temp = ((samplesIn[bytesPerSample*i+x] & lower8Mask) << upShift);
                            totalTemp = totalTemp | temp;
                        }
                        sampleData[i] = totalTemp;
                    }
                }
                else {
                    for(int i = 0; i < framesRead*channels; i++) {
                        int lower8Mask = 255;
                        int temp = 0;
                        int totalTemp = 0;
                        for(int x = 0; x < bytesPerSample; x++) {
                            int upShift = 8*x;
                            if(x == bytesPerSample-1)//don't mask...we want sign
                                temp = ((samplesIn[bytesPerSample*i+x]) << upShift);
                            else
                                temp = ((samplesIn[bytesPerSample*i+x] & lower8Mask) << upShift);
                            totalTemp = totalTemp | temp;
                        }
                        sampleData[i] = totalTemp;
                    }
                }
                if(framesRead > 0) {
                   flac.addSamples(sampleData, framesRead);
                   unencodedSamples += framesRead;
                }
                //if(unencodedSamples > blockSize*100) {
                    if(useThreads)//Thread.yield();//
                        unencodedSamples -= flac.t_encodeSamples(unencodedSamples, false);
                    else
                        unencodedSamples -= flac.encodeSamples(unencodedSamples, false);
                    totalSamples += unencodedSamples;
                    //unencodedSamples = 0;

                //}
                //System.err.println("read : "+ samplesRead);
            }
            totalSamples += unencodedSamples;
            if(useThreads)
                unencodedSamples -= flac.t_encodeSamples(unencodedSamples, true);
            else
                unencodedSamples -= flac.encodeSamples(unencodedSamples, true);
            //unencodedSamples = 0;
            lastTotalSamples = totalSamples;
        }
        catch(IOException e) {
            status = Status.FILE_IO_ERROR;
        }
        catch(Exception e) {
            status = Status.GENERAL_ERROR;
            String message = e.getMessage();
            if(message == null) {            
                e.printStackTrace();
            }
            else if(message.equals(Status.UNSUPPORTED_SAMPLE_SIZE.name()))
                status = Status.UNSUPPORTED_SAMPLE_SIZE;
        }

        //System.err.print("LastTotalSamples: "+lastTotalSamples);
        return status;
    }

    /**
     * Get the total number of samples encoded in last encode.  This is here
     * primarily for use as a sanity check during debugging.
     *
     * @return Total number of samples encoded in last encode attempt.
     */
    public int getLastTotalSamplesEncoded() {
        return this.lastTotalSamples;
    }
}

Source: (StackOverflow)

How to encode wav files to flac format on android

I have a bytearray that holds an wav audio stream.

Is there a way on android system to convert the wav file to a flac file?

I found some example code from FlacEncoder library but this library assumes as far as I see the use of some audio classes from javax.

These are not available on android.

Is there some other library or some example code for android?

Thanks!


Source: (StackOverflow)

.NET: How can I convert an mp3 or a wav file to .flac

I need to write a utility in c# that uses Google Speech Api to convert speech from an audio file into text. As far as I know, Google only accepts .flac format for this api. Unfortunately, I have .wav and .mp3 audio files. So I am trying to find out if there is a way for me to convert mp3 to flac in .NET. I looked at NAudio, but it doesn't seem to be working with flac files.


Source: (StackOverflow)

avconv : flac to ogg conversion with metadata kept

I'm currently writing a command line tool to convert a input music library with various formats (flac / ogg / mp3 / ...) to an output music library of a given format (flac / ogg / mp3). I've based it on avconv (or ffmpeg if avconv is not available) since it is the most complete command line converter i've found. My script is available at this URL (GitHub):

https://github.com/biapy/howto.biapy.com/blob/master/various/mussync-tools

I'm trying to pass the metadata from the input library files to the output/converted library files.

I've come up with this code:

 local MAP_METADATA=' 0:g'
  # Specific needs for some input formats/
  case "${INPUT_FILE_MIMETYPE}" in
    'application/ogg' )
      # Get input metadata from first audio stream and direct it to global.
      MAP_METADATA=' 0:s:0'
      ;;

    * )
      # Do nothing.
      # MAP_METADATA=' 0:g'
      ;;
  esac

  # Specific needs for some output formats/
  local OUTPUT_OPTIONS=""
  case "${OUTPUT_FORMAT}" in
    'flac' )
      # No encoding options needed.
      ENCODING_OPTIONS=""
      ;;

    'ogg' )
      # Set vorbis as default codec for ogg.
      OUTPUT_OPTIONS="-codec:a libvorbis -f ${OUTPUT_FORMAT}"
      # Map input metadata to all audio streams in ogg container.
      MAP_METADATA=":s:a ${MAP_METADATA}"
      ;;

    * )
      # Do nothing.
      # MAP_METADATA="${MAP_METADATA}"
      OUTPUT_OPTIONS="-f ${OUTPUT_FORMAT}"
      ;;
  esac

  # Dangerous solution for mp3 cbr format:
  # Write output on pipe and then directed to file.
  # For cbr format for mp3 files. Harmless for other formats.
  # See: http://ffmpeg.zeranoe.com/forum/viewtopic.php?f=7&t=377
  #
  # What about log output ? how to prevent it from being included in
  # the resulting output file ?

  if ! command ${AVCONV} -i "${INPUT_FILE}" \
             -vn -sn \
            -map_metadata${MAP_METADATA} \
            -loglevel "${LOG_LEVEL}" \
            ${AVCONV_OPTIONS} \
            ${OUTPUT_OPTIONS} \
            ${ENCODING_OPTIONS} \
            "${OUTPUT_TEMP_FILE}"; then
    test "${QUIET}" != 'True' && echo "Failed."
    test -e "${OUTPUT_TEMP_FILE}" && command rm "${OUTPUT_TEMP_FILE}"

    return 1
  else
    test "${QUIET}" != 'True' && echo "Done."

    # Test if fix for MP3 VBR is needed.
    # See: http://ffmpeg.zeranoe.com/forum/viewtopic.php?f=7&t=377
    if [ "${OUTPUT_FORMAT}" = 'mp3' -a "${ENCODING_MODE}" != 'CBR' ]; then
      # Output file is MP3 and VBR. Apply header fix.
      if [ "${VERBOSE}" = 'True' ]; then
        command vbrfix "${OUTPUT_TEMP_FILE}" "${OUTPUT_FILE}"
      else
        command vbrfix "${OUTPUT_TEMP_FILE}" "${OUTPUT_FILE}"
      fi
    else
      # Nothing to do but rename the file.
      command mv "${OUTPUT_TEMP_FILE}" "${OUTPUT_FILE}"
    fi

    # Delete temporary file if it is still present.
    test -e "${OUTPUT_TEMP_FILE}" && command rm "${OUTPUT_TEMP_FILE}"

    # Fetch cover art from input file.
    transfert_images "${INPUT_FILE}" "${OUTPUT_FILE}"
  fi

My problem is that when converting a flac to ogg with the avconv version available on Ubuntu 13.10 Saucy Salamander, the metadata are not kept, despite this option (copy global metadata from input flac file to all audio streams of output ogg file):

--map_metadata:s:a 0:g

Does one of you know the correct --map_metadata option for copying metadata from a flac input file to a ogg output file when converting ?

ps: additional question: how to prevent avconv generated CBR mp3 files to have a VBR header ?

pps: i'm aware of tools such as beets, but i've yet to see a specialized command line tool that do this task.


Source: (StackOverflow)