<p dir="ltr">Thanks for reply...<br>
The code is only sample, and method writeaudiochunk is get called from outside. <br>
I am using directshow graph as audio source.<br>
if you want full code I can give it to you.</p>
<p dir="ltr">Now the sample is working. But I have recorded audio for 2 min but output file has only 3 sec duration and audio is also so fast...</p>
<p dir="ltr">Can you make some suggestions...</p>
<div class="gmail_extra"><br><div class="gmail_quote">On 20 Feb 2017 22:42, "Gonzalo Garramuno" <<a href="mailto:ggarra13@gmail.com">ggarra13@gmail.com</a>> wrote:<br type="attribution"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div dir="auto">I am unable to compile your code, but at first glance you are missing the main loop. The one that would call writeaudiochunk.</div><div class="gmail_extra"><br><div class="gmail_quote">El feb. 20, 2017 12:41 PM, "Prakash Rokade" <<a href="mailto:prakash.rokade420@gmail.com" target="_blank">prakash.rokade420@gmail.com</a>> escribió:<br type="attribution"><blockquote class="m_-9186720474361670380quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div dir="ltr"><div><div>Hiii Gonzalo Garramuño,<br><br></div>I have modified the code but there is issue that i am not able to figure out.<br></div>No error while encoding, resampling , and writting the audio data. But output file only have the 1 sec audio. can you check the code and suggest some changes.<br><br>ref struct AudioWriterData<div class="m_-9186720474361670380quoted-text"><br>    {<br>        public:<br>            Ffmpeg::AVFormatContext*        FormatContext;<br>            <br>            Ffmpeg::AVStream*                AudioStream;<br>            Ffmpeg::AVFrame*                AudioFrame;<br>            Ffmpeg::AVCodec                *Audio_Codec;<br><br>            int AudioBitRate;<br>            int SampleRate;<br>            int Channels;<br>        <br>            int AudioReceived;<br>            int AudioWritten;<br><br></div><div class="m_-9186720474361670380quoted-text">            int64_t next_pts;<br>            int samples_count;<br><br>            Ffmpeg::AVFrame *tmp_frame;<br><br>            float t, tincr, tincr2;<br>            struct Ffmpeg::SwsContext *sws_ctx;<br>            struct Ffmpeg::SwrContext *swr_ctx;<br><br>            double PreviousAudioDts;<br><br></div>            double EncodedAudioFrame;<div class="m_-9186720474361670380quoted-text"><br><br>            AudioWriterData()<br>            {<br>                FormatContext = NULL;<br>                <br>                AudioStream = NULL;<br><br>                Audio_Codec = NULL;<br><br>                AudioFrame = NULL;<br>            <br>                AudioReceived = 0;<br>                AudioWritten = 0;<br></div>                EncodedAudioFrame = 0;<br>            }<br>    };<br>    <br>    <br>    //Open the audio file with specified settings<br>    void AudioWriter::Open(String^ fileName, AudioCodec audioCodec, int audioBitrate, int sampleRate, int channels)<br>    {<br>        CheckIfDisposed();<br><br>        Close();<br><br>        data = gcnew AudioWriterData();<div class="m_-9186720474361670380quoted-text"><br>        bool success = false;<br><br>        if (((int)audioCodec < -1) || ((int)audioCodec >= AUDIO_CODECS_COUNT))<br>            throw gcnew ArgumentException("Invalid audio codec is specified.");<br><br>        m_acodec = audioCodec;<br>        m_audioBitrate = audioBitrate;<br>        m_sampleRate = sampleRate;<br>        m_channels = channels;<br><br>        data->AudioBitRate = audioBitrate;<br>        data->SampleRate = sampleRate;<br>        data->Channels = channels;<br><br>        char* nativeFileName = (char*)System::Runtime::Intero<wbr>pServices::Marshal::StringToHG<wbr>lobalAnsi(fileName).ToPointer(<wbr>);<br><br>        try<br>        {<br>            Ffmpeg::AVOutputFormat* outputFormat = Ffmpeg::av_guess_format(NULL, nativeFileName, NULL);<br><br>            if (!outputFormat)<br>            {<br>                outputFormat = Ffmpeg::av_guess_format("mp3", NULL, NULL);<br><br>                if (!outputFormat)<br>                    throw gcnew Exception("Cannot find suitable output format.");<br>            }<br><br>            data->FormatContext = Ffmpeg::avformat_alloc_context<wbr>();<br><br>            if (!data->FormatContext)<br>                throw gcnew Exception("Cannot allocate format context.");<br><br>            data->FormatContext->oformat = outputFormat;<br>            strcpy_s(data->FormatContext-><wbr>filename, nativeFileName);<br><br></div>            Ffmpeg::AVCodecID avcodecid = (audioCodec == AudioCodec::Default) ? outputFormat->audio_codec : (Ffmpeg::AVCodecID) audio_codecs[(int)audioCodec];<br>            data->FormatContext->oformat-><wbr>audio_codec = avcodecid;<br><br>            add_stream(data, data->FormatContext, data->Audio_Codec, avcodecid);<br><br>            open_audio(data->FormatContext<wbr>, data->Audio_Codec, data);<div class="m_-9186720474361670380quoted-text"><br><br>            Ffmpeg::av_dump_format(data->F<wbr>ormatContext, 0, nativeFileName, 1);<br><br>            if (!(outputFormat->flags & AVFMT_NOFILE))<br>            {<br>                if (Ffmpeg::avio_open(&data->Form<wbr>atContext->pb, nativeFileName, AVIO_FLAG_WRITE) < 0)<br></div>                    throw gcnew System::IO::IOException("Canno<wbr>t open the audio file.");<div class="m_-9186720474361670380quoted-text"><br>            }<br><br>            Ffmpeg::avformat_write_header(<wbr>data->FormatContext, NULL);<br><br>            success = true;<br>        }<br>        finally<br>        {<br>            nativeFileName = NULL;<br>            delete[] nativeFileName;<br><br>            if (!success)<br>                Close();<br>        }<br>    }<br>    <br></div>    static void add_stream(AudioWriterData^ ost, Ffmpeg::AVFormatContext *oc, Ffmpeg::AVCodec *codec, enum Ffmpeg::AVCodecID codec_id)<br>    {<br>        Ffmpeg::AVCodecContext *c;<br>        int i;<br><br>        codec = Ffmpeg::avcodec_find_encoder(c<wbr>odec_id);<br><br>        if (!(codec)) <br>            throw gcnew Exception("Invalid audio codec is specified.");<br><br>        ost->AudioStream = Ffmpeg::avformat_new_stream(oc<wbr>, codec);<br><br>        if (!ost->AudioStream)<br>            throw gcnew Exception("Unable to add audio stream.");<br><br>        ost->AudioStream->id = oc->nb_streams - 1;<br>        c = ost->AudioStream->codec;<br>        c->sample_fmt = (codec)->sample_fmts ? (codec)->sample_fmts[0] : Ffmpeg::AV_SAMPLE_FMT_FLTP;<br>        c->bit_rate = ost->AudioBitRate;<br>        c->sample_rate = 44100;<br>        if ((codec)->supported_samplerate<wbr>s) <br>        {<br>            c->sample_rate = (codec)->supported_samplerates<wbr>[0];<br>            for (i = 0; (codec)->supported_samplerates<wbr>[i]; i++) <br>            {<br>                if ((codec)->supported_samplerate<wbr>s[i] == 44100)<br>                c->sample_rate = 44100;<br>            }<br>        }<br>        c->channels = Ffmpeg::av_get_channel_layout_<wbr>nb_channels(c->channel_layout)<wbr>;<br>        c->channel_layout = AV_CH_LAYOUT_STEREO;<br>        if ((codec)->channel_layouts) <br>        {<br>            c->channel_layout = (codec)->channel_layouts[0];<br>            for (i = 0; (codec)->channel_layouts[i]; i++) <br>            {<br>                if ((codec)->channel_layouts[i] == AV_CH_LAYOUT_STEREO)<br>                    c->channel_layout = AV_CH_LAYOUT_STEREO;<br>            }<br>        }<br>        c->channels = Ffmpeg::av_get_channel_layout_<wbr>nb_channels(c->channel_layout)<wbr>;<br>        ost->AudioStream-><a href="http://time_base.nu">time_base.nu</a><wbr>m = 1;<br>        ost->AudioStream-><a href="http://time_base.de">time_base.de</a><wbr>n = c->sample_rate;<br>        <br>        if (oc->oformat->flags & AVFMT_GLOBALHEADER)<br>            c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;<br>    }<br><br>    static Ffmpeg::AVFrame *alloc_audio_frame(enum Ffmpeg::AVSampleFormat sample_fmt,uint64_t channel_layout,int sample_rate, int nb_samples)<br>    {<br>        Ffmpeg::AVFrame *frame = Ffmpeg::av_frame_alloc();<br>        int ret;<br>        if (!frame) <br>            throw gcnew Exception("Unable to allocate frame.");<br>        <br>        frame->format = sample_fmt;<br>        frame->channel_layout = channel_layout;<br>        frame->sample_rate = sample_rate;<br>        frame->nb_samples = nb_samples;<br>        <br>        if (nb_samples) <br>        {<br>            ret = av_frame_get_buffer(frame, 0);<br>            if (ret < 0) <br>                throw gcnew Exception("Unable to buffer frame.");<br>        }<br>        <br>        return frame;<br>    }<br>    <br>    static void open_audio(Ffmpeg::AVFormatCon<wbr>text *oc, Ffmpeg::AVCodec *codec, AudioWriterData^ ost)<br>    {<br>        Ffmpeg::AVCodecContext *c;<br>        int nb_samples;<br>        int ret;<br>        c = ost->AudioStream->codec;<br><br>        ret = avcodec_open2(c, codec, NULL);<div class="m_-9186720474361670380quoted-text"><br>        if (ret < 0)<br>            throw gcnew Exception("Cannot open audio codec.");<br><br></div>        ost->t = 0;<br>        ost->tincr = 2 * M_PI * 110.0 / c->sample_rate;<br>        ost->tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;<br>        <br>        if (c->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SI<wbr>ZE)<br>            nb_samples = 10000;<br>        else<br>            nb_samples = c->frame_size;<br>        <br>        ost->AudioFrame = alloc_audio_frame(c->sample_fm<wbr>t, c->channel_layout, c->sample_rate, nb_samples);<br>        ost->tmp_frame = alloc_audio_frame(Ffmpeg::AV_S<wbr>AMPLE_FMT_S16, c->channel_layout, c->sample_rate, nb_samples);<br>                <br>        ost->swr_ctx = Ffmpeg::swr_alloc();<br>        if (!ost->swr_ctx)<br>            throw gcnew Exception("Could not allocate resampler context.");<br>                <br>        Ffmpeg::av_opt_set_int(ost->sw<wbr>r_ctx, "in_channel_count", c->channels, 0);<br>        Ffmpeg::av_opt_set_int(ost->sw<wbr>r_ctx, "in_sample_rate", c->sample_rate, 0);<br>        Ffmpeg::av_opt_set_sample_fmt(<wbr>ost->swr_ctx, "in_sample_fmt", Ffmpeg::AV_SAMPLE_FMT_S16, 0);<br>        Ffmpeg::av_opt_set_int(ost->sw<wbr>r_ctx, "out_channel_count", c->channels, 0);<br>        Ffmpeg::av_opt_set_int(ost->sw<wbr>r_ctx, "out_sample_rate", c->sample_rate, 0);<br>        Ffmpeg::av_opt_set_sample_fmt(<wbr>ost->swr_ctx, "out_sample_fmt", c->sample_fmt, 0);<br>                <br>        if ((ret = Ffmpeg::swr_init(ost->swr_ctx)<wbr>) < 0)<br>            throw gcnew Exception("Failed to initialize the resampling context.");<br>    }<br>    <br>    void AudioWriter::WriteAudioChunk(I<wbr>ntPtr chunk, int lenght)<br>    {<br>        uint8_t *audioData = reinterpret_cast<uint8_t*>(sta<wbr>tic_cast<void*>(chunk));<br><br>        int buffer_size = Ffmpeg::av_samples_get_buffer_<wbr>size(NULL, data->tmp_frame->channels, data->tmp_frame->nb_samples,<br>            data->AudioStream->codec->samp<wbr>le_fmt, 0);<br><br>        uint8_t *buf = reinterpret_cast<uint8_t*>(sta<wbr>tic_cast<void*>(chunk));<br>        int ret = Ffmpeg::avcodec_fill_audio_fra<wbr>me(data->tmp_frame, data->Channels, data->AudioStream->codec->samp<wbr>le_fmt, buf, buffer_size, 1);<div class="m_-9186720474361670380quoted-text"><br>        if (!ret)<br>            throw gcnew System::IO::IOException("A video file was not opened yet.");<br><br></div>        write_audio_frame(data->Format<wbr>Context, data, audioData);<br>    }<br>    <br>    static int write_audio_frame(Ffmpeg::AVFo<wbr>rmatContext *oc, AudioWriterData^ ost, uint8_t *audioData)<br>    {<br>        Ffmpeg::AVCodecContext *c;<br>        Ffmpeg::AVPacket pkt = { 0 };<br>        int ret;<br>        int got_packet;<br>        int dst_nb_samples;<br><br>        Ffmpeg::av_init_packet(&pkt);<br>        c = ost->AudioStream->codec;<br>        <br>        Ffmpeg::AVFrame *frame = ost->tmp_frame;<br><br>        if (frame)<br>        {<br>            dst_nb_samples = Ffmpeg::av_rescale_rnd(swr_get<wbr>_delay(ost->swr_ctx, c->sample_rate) + frame->nb_samples,<br>                c->sample_rate, c->sample_rate, Ffmpeg::AV_ROUND_UP);<br>            if (dst_nb_samples != frame->nb_samples)<br>                throw gcnew Exception("dst_nb_samples != frame->nb_samples");<br><br>            ret = Ffmpeg::av_frame_make_writable<wbr>(ost->AudioFrame);<br>            if (ret < 0)<br>                throw gcnew Exception("Unable to make writable.");<br><br>            ret = swr_convert(ost->swr_ctx, ost->AudioFrame->data, dst_nb_samples, (const uint8_t **)frame->data, frame->nb_samples);<br>            if (ret < 0) <br>                throw gcnew Exception("Unable to convert to destination format.");<br>            <br>            frame = ost->AudioFrame;<br><br>            Ffmpeg::AVRational timebase = { 1, c->sample_rate };<br>            frame->pts = Ffmpeg::av_rescale_q(ost->samp<wbr>les_count, timebase, c->time_base);<br>            ost->samples_count += dst_nb_samples;<br>        }<br><br>        ret = avcodec_encode_audio2(c, &pkt, frame, &got_packet);<br>        if (ret < 0) <br>            throw gcnew Exception("Error encoding audio frame.");<br><br>        if (got_packet) <br>        {<br>            Console::WriteLine("Audio packet encode successfully.");<br>            ret = write_frame(oc, &c->time_base, ost->AudioStream, &pkt);<br>            if (ret < 0)<br>                Console::WriteLine("Audio is not written.");<br>        }<br>        else<br>            Console::WriteLine("Audio packet encode failed.");<br><br>        return (ost->AudioFrame || got_packet) ? 0 : 1;<br>    }<br><br>    static int write_frame(Ffmpeg::AVFormatCo<wbr>ntext *fmt_ctx, const Ffmpeg::AVRational *time_base, Ffmpeg::AVStream *st, Ffmpeg::AVPacket *pkt)<br>    {<br>        Ffmpeg::av_packet_rescale_ts(p<wbr>kt, *time_base, st->time_base);<br>        pkt->stream_index = st->index;<br>        return Ffmpeg::av_interleaved_write_f<wbr>rame(fmt_ctx, pkt);<br>    }<br></div><div class="gmail_extra"><br><div class="gmail_quote"><div class="m_-9186720474361670380elided-text">On 16 February 2017 at 03:13, Gonzalo Garramuño <span dir="ltr"><<a href="mailto:ggarra13@gmail.com" target="_blank">ggarra13@gmail.com</a>></span> wrote:<br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div class="m_-9186720474361670380elided-text">
  
    
  
  <div bgcolor="#FFFFFF" text="#000000">
    <p><br>
    </p>
    <br>
    <div class="m_-9186720474361670380m_-5977202174146604855m_8816357505044468833moz-cite-prefix">El 15/02/17 a las 03:58, Prakash Rokade
      escribió:<br>
    </div><span>
    <blockquote type="cite">
      <div dir="ltr">
        <div>Thanks Gonzalo,</div>
        <div><br>
        </div>
        <div>According to your suggestion i have written the below code
          can you check ones, because audio is written but in output
          file no audio is present.</div>
        <div><span style="font-size:12.8px"></span><br style="font-size:12.8px">
        </div>
      </div>
    </blockquote></span>
    You are opening the stream with AV_SAMPLE_FMT_S16 and then using
    sample_fmt[0]. That's inconsistent to say the least.<br>
    You are not using swresample to take one audio format to another.<br>
    You have a swscale ptr which has nothing to do with audio.<br>
    You are using the new API but are not handling the AVERROR(EAGAIN)
    cases.  For this trial, use the old api which is more reliable for
    muxing.<br>
    Try to get the sample in doc/examples working and slowly modify it
    to fit your need.<span class="m_-9186720474361670380m_-5977202174146604855HOEnZb"><font color="#888888"><br>
    <pre class="m_-9186720474361670380m_-5977202174146604855m_8816357505044468833moz-signature" cols="72">-- 
Gonzalo Garramuño</pre>
  </font></span></div>

<br></div><div class="m_-9186720474361670380quoted-text">______________________________<wbr>_________________<br>
Libav-user mailing list<br>
<a href="mailto:Libav-user@ffmpeg.org" target="_blank">Libav-user@ffmpeg.org</a><br>
<a href="http://ffmpeg.org/mailman/listinfo/libav-user" rel="noreferrer" target="_blank">http://ffmpeg.org/mailman/list<wbr>info/libav-user</a><br>
<br></div></blockquote></div><br></div>
<br>______________________________<wbr>_________________<br>
Libav-user mailing list<br>
<a href="mailto:Libav-user@ffmpeg.org" target="_blank">Libav-user@ffmpeg.org</a><br>
<a href="http://ffmpeg.org/mailman/listinfo/libav-user" rel="noreferrer" target="_blank">http://ffmpeg.org/mailman/list<wbr>info/libav-user</a><br>
<br></blockquote></div><br></div>
<br>______________________________<wbr>_________________<br>
Libav-user mailing list<br>
<a href="mailto:Libav-user@ffmpeg.org">Libav-user@ffmpeg.org</a><br>
<a href="http://ffmpeg.org/mailman/listinfo/libav-user" rel="noreferrer" target="_blank">http://ffmpeg.org/mailman/<wbr>listinfo/libav-user</a><br>
<br></blockquote></div></div>