Recherche avancée

Médias (91)

Autres articles (20)

  • Publier sur MédiaSpip

    13 juin 2013

    Puis-je poster des contenus à partir d’une tablette Ipad ?
    Oui, si votre Médiaspip installé est à la version 0.2 ou supérieure. Contacter au besoin l’administrateur de votre MédiaSpip pour le savoir

  • Organiser par catégorie

    17 mai 2013, par

    Dans MédiaSPIP, une rubrique a 2 noms : catégorie et rubrique.
    Les différents documents stockés dans MédiaSPIP peuvent être rangés dans différentes catégories. On peut créer une catégorie en cliquant sur "publier une catégorie" dans le menu publier en haut à droite ( après authentification ). Une catégorie peut être rangée dans une autre catégorie aussi ce qui fait qu’on peut construire une arborescence de catégories.
    Lors de la publication prochaine d’un document, la nouvelle catégorie créée sera proposée (...)

  • Les thèmes de MediaSpip

    4 juin 2013

    3 thèmes sont proposés à l’origine par MédiaSPIP. L’utilisateur MédiaSPIP peut rajouter des thèmes selon ses besoins.
    Thèmes MediaSPIP
    3 thèmes ont été développés au départ pour MediaSPIP : * SPIPeo : thème par défaut de MédiaSPIP. Il met en avant la présentation du site et les documents média les plus récents ( le type de tri peut être modifié - titre, popularité, date) . * Arscenic : il s’agit du thème utilisé sur le site officiel du projet, constitué notamment d’un bandeau rouge en début de page. La structure (...)

Sur d’autres sites (5622)

  • Screeching white sound coming while playing audio as a raw stream

    27 avril 2020, par Sri Nithya Sharabheshwarananda

    I. Background

    



      

    1. I am trying to make an application which helps to match subtitles to the audio waveform very accurately at the waveform level, at the word level or even at the character level.
    2. 


    3. The audio is expected to be Sanskrit chants (Yoga, rituals etc.) which are extremely long compound words [ example - aṅganyā-sokta-mātaro-bījam is traditionally one word broken only to assist reading ]
    4. 


    5. The input transcripts / subtitles might be roughly in sync at the sentence/verse level but surely would not be in sync at the word level.
    6. 


    7. The application should be able to figure out points of silence in the audio waveform, so that it can guess the start and end points of each word (or even letter/consonant/vowel in a word), such that the audio-chanting and visual-subtitle at the word level (or even at letter/consonant/vowel level) perfectly match, and the corresponding UI just highlights or animates the exact word (or even letter) in the subtitle line which is being chanted at that moment, and also show that word (or even the letter/consonant/vowel) in bigger font. This app's purpose is to assist learning Sanskrit chanting.
    8. 


    9. It is not expected to be a 100% automated process, nor 100% manual but a mix where the application should assist the human as much as possible.
    10. 


    



    II. Following is the first code I wrote for this purpose, wherein

    



      

    1. First I open a mp3 (or any audio format) file,
    2. 


    3. Seek to some arbitrary point in the timeline of the audio file // as of now playing from zero offset
    4. 


    5. Get the audio data in raw format for 2 purposes - (1) playing it and (2) drawing the waveform.
    6. 


    7. Playing the raw audio data using standard java audio libraries
    8. 


    



    III. The problem I am facing is, between every cycle there is screeching sound.

    



      

    • Probably I need to close the line between cycles ? Sounds simple, I can try.
    • 


    • But I am also wondering if this overall approach itself is correct ? Any tip, guide, suggestion, link would be really helpful.
    • 


    • Also I just hard coded the sample-rate etc ( 44100Hz etc. ), are these good to set as default presets or it should depend on the input format ?
    • 


    



    IV. Here is the code

    



    import com.github.kokorin.jaffree.StreamType;
import com.github.kokorin.jaffree.ffmpeg.FFmpeg;
import com.github.kokorin.jaffree.ffmpeg.FFmpegProgress;
import com.github.kokorin.jaffree.ffmpeg.FFmpegResult;
import com.github.kokorin.jaffree.ffmpeg.NullOutput;
import com.github.kokorin.jaffree.ffmpeg.PipeOutput;
import com.github.kokorin.jaffree.ffmpeg.ProgressListener;
import com.github.kokorin.jaffree.ffprobe.Stream;
import com.github.kokorin.jaffree.ffmpeg.UrlInput;
import com.github.kokorin.jaffree.ffprobe.FFprobe;
import com.github.kokorin.jaffree.ffprobe.FFprobeResult;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;


public class FFMpegToRaw {
    Path BIN = Paths.get("f:\\utilities\\ffmpeg-20190413-0ad0533-win64-static\\bin");
    String VIDEO_MP4 = "f:\\org\\TEMPLE\\DeviMahatmyamRecitationAudio\\03_01_Devi Kavacham.mp3";
    FFprobe ffprobe;
    FFmpeg ffmpeg;

    public void basicCheck() throws Exception {
        if (BIN != null) {
            ffprobe = FFprobe.atPath(BIN);
        } else {
            ffprobe = FFprobe.atPath();
        }
        FFprobeResult result = ffprobe
                .setShowStreams(true)
                .setInput(VIDEO_MP4)
                .execute();

        for (Stream stream : result.getStreams()) {
            System.out.println("Stream " + stream.getIndex()
                    + " type " + stream.getCodecType()
                    + " duration " + stream.getDuration(TimeUnit.SECONDS));
        }    
        if (BIN != null) {
            ffmpeg = FFmpeg.atPath(BIN);
        } else {
            ffmpeg = FFmpeg.atPath();
        }

        //Sometimes ffprobe can't show exact duration, use ffmpeg trancoding to NULL output to get it
        final AtomicLong durationMillis = new AtomicLong();
        FFmpegResult fFmpegResult = ffmpeg
                .addInput(
                        UrlInput.fromUrl(VIDEO_MP4)
                )
                .addOutput(new NullOutput())
                .setProgressListener(new ProgressListener() {
                    @Override
                    public void onProgress(FFmpegProgress progress) {
                        durationMillis.set(progress.getTimeMillis());
                    }
                })
                .execute();
        System.out.println("audio size - "+fFmpegResult.getAudioSize());
        System.out.println("Exact duration: " + durationMillis.get() + " milliseconds");
    }

    public void toRawAndPlay() throws Exception {
        ProgressListener listener = new ProgressListener() {
            @Override
            public void onProgress(FFmpegProgress progress) {
                System.out.println(progress.getFrame());
            }
        };

        // code derived from : https://stackoverflow.com/questions/32873596/play-raw-pcm-audio-received-in-udp-packets

        int sampleRate = 44100;//24000;//Hz
        int sampleSize = 16;//Bits
        int channels   = 1;
        boolean signed = true;
        boolean bigEnd = false;
        String format  = "s16be"; //"f32le"

        //https://trac.ffmpeg.org/wiki/audio types
        final AudioFormat af = new AudioFormat(sampleRate, sampleSize, channels, signed, bigEnd);
        final DataLine.Info info = new DataLine.Info(SourceDataLine.class, af);
        final SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);

        line.open(af, 4096); // format , buffer size
        line.start();

        OutputStream destination = new OutputStream() {
            @Override public void write(int b) throws IOException {
                throw new UnsupportedOperationException("Nobody uses thi.");
            }
            @Override public void write(byte[] b, int off, int len) throws IOException {
                String o = new String(b);
                boolean showString = false;
                System.out.println("New output ("+ len
                        + ", off="+off + ") -> "+(showString?o:"")); 
                // output wave form repeatedly

                if(len%2!=0) {
                    len -= 1;
                    System.out.println("");
                }
                line.write(b, off, len);
                System.out.println("done round");
            }
        };

        // src : http://blog.wudilabs.org/entry/c3d357ed/?lang=en-US
        FFmpegResult result = FFmpeg.atPath(BIN).
            addInput(UrlInput.fromPath(Paths.get(VIDEO_MP4))).
            addOutput(PipeOutput.pumpTo(destination).
                disableStream(StreamType.VIDEO). //.addArgument("-vn")
                setFrameRate(sampleRate).            //.addArguments("-ar", sampleRate)
                addArguments("-ac", "1").
                setFormat(format)              //.addArguments("-f", format)
            ).
            setProgressListener(listener).
            execute();

        // shut down audio
        line.drain();
        line.stop();
        line.close();

        System.out.println("result = "+result.toString());
    }

    public static void main(String[] args) throws Exception {
        FFMpegToRaw raw = new FFMpegToRaw();
        raw.basicCheck();
        raw.toRawAndPlay();
    }
}



    



    Thank You

    


  • JavaCPP FFMpeg to JavaSound

    8 août 2020, par TW2

    I have a problem to be able to read audio using JavaCPP FFMpeg library. I don’t know how to pass it to java sound and I don’t know too if my code is correct.

    


    Let’s see the more important part of my code (video is OK so I drop this)  :

    


    The variables  :

    


    //==========================================================================&#xA;// FFMpeg 4.x - Video and Audio&#xA;//==========================================================================&#xA;&#xA;private final AVFormatContext   pFormatCtx = new AVFormatContext(null);&#xA;private final AVDictionary      OPTIONS_DICT = null;&#xA;private AVPacket                pPacket = new AVPacket();&#xA;    &#xA;//==========================================================================&#xA;// FFMpeg 4.x - Audio&#xA;//==========================================================================&#xA;    &#xA;private AVCodec                 pAudioCodec;&#xA;private AVCodecContext          pAudioCodecCtx;&#xA;private final List<streaminfo>  audioStreams = new ArrayList&lt;>();&#xA;private int                     audio_data_size;&#xA;private final BytePointer       audio_data = new BytePointer(0);&#xA;private int                     audio_ret;&#xA;private AVFrame                 pAudioDecodedFrame = null;&#xA;private AVCodecParserContext    pAudioParser;&#xA;private SwrContext              audio_swr_ctx = null;&#xA;</streaminfo>

    &#xA;

    Then I call prepare functions in this order  :

    &#xA;

    private void prepareFirst() throws Exception{&#xA;    oldFile = file;&#xA;            &#xA;    // Initialize packet and check for error&#xA;    pPacket = av_packet_alloc();&#xA;    if(pPacket == null){&#xA;        throw new Exception("ALL: Couldn&#x27;t allocate packet");&#xA;    }&#xA;&#xA;    // Open video file&#xA;    if (avformat_open_input(pFormatCtx, file.getPath(), null, null) != 0) {&#xA;        throw new Exception("ALL: Couldn&#x27;t open file");&#xA;    }&#xA;&#xA;    // Retrieve stream information&#xA;    if (avformat_find_stream_info(pFormatCtx, (PointerPointer)null) &lt; 0) {&#xA;        throw new Exception("ALL: Couldn&#x27;t find stream information");&#xA;    }&#xA;&#xA;    // Dump information about file onto standard error&#xA;    av_dump_format(pFormatCtx, 0, file.getPath(), 0);&#xA;&#xA;    // Find the first audio/video stream&#xA;    for (int i = 0; i &lt; pFormatCtx.nb_streams(); i&#x2B;&#x2B;) {&#xA;        switch(pFormatCtx.streams(i).codecpar().codec_type()){&#xA;            case AVMEDIA_TYPE_VIDEO -> videoStreams.add(new StreamInfo(i, pFormatCtx.streams(i)));&#xA;            case AVMEDIA_TYPE_AUDIO -> audioStreams.add(new StreamInfo(i, pFormatCtx.streams(i)));&#xA;        }&#xA;    }&#xA;    &#xA;    if(videoStreams.isEmpty() &amp;&amp; type != PlayType.AudioOnly){&#xA;        throw new Exception("Didn&#x27;t find an audio stream");&#xA;    }&#xA;    if(audioStreams.isEmpty() &amp;&amp; type != PlayType.VideoOnly){&#xA;        throw new Exception("Didn&#x27;t find a video stream");&#xA;    }&#xA;}&#xA;&#xA;private void prepareAudio() throws Exception{&#xA;    //&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#x2B;&#xA;    // AUDIO&#xA;    //------------------------------------------------------------------&#xA;&#xA;    if(audioStreams.isEmpty() == false){&#xA;        //===========================&#xA;        //------------&#xA;        &#xA;//                // Let&#x27;s search for AVCodec&#xA;//                pAudioCodec = avcodec_find_decoder(pFormatCtx.streams(audioStreams.get(0).getStreamIndex()).codecpar().codec_id());&#xA;//                if (pAudioCodec == null) {&#xA;//                    throw new Exception("AUDIO: Unsupported codec or not found!");&#xA;//                }&#xA;//&#xA;//                // Let&#x27;s alloc AVCodecContext&#xA;//                pAudioCodecCtx = avcodec_alloc_context3(pAudioCodec);&#xA;//                if (pAudioCodecCtx == null) {            &#xA;//                    throw new Exception("AUDIO: Unallocated codec context or not found!");&#xA;//                }&#xA;        &#xA;        // Get a pointer to the codec context for the video stream&#xA;        pAudioCodecCtx = pFormatCtx.streams(audioStreams.get(0).getStreamIndex()).codec();&#xA;&#xA;        // Find the decoder for the video stream&#xA;        pAudioCodec = avcodec_find_decoder(pAudioCodecCtx.codec_id());&#xA;        if (pAudioCodec == null) {&#xA;            throw new Exception("AUDIO: Unsupported codec or not found!");&#xA;        }&#xA;&#xA;        //===========================&#xA;        //------------&#xA;&#xA;        /* open it */&#xA;        if (avcodec_open2(pAudioCodecCtx, pAudioCodec, OPTIONS_DICT) &lt; 0) {&#xA;            throw new Exception("AUDIO: Could not open codec");&#xA;        }&#xA;&#xA;        pAudioDecodedFrame = av_frame_alloc();&#xA;        if (pAudioDecodedFrame == null){&#xA;            throw new Exception("AUDIO: DecodedFrame allocation failed");&#xA;        }&#xA;&#xA;        audio_swr_ctx = swr_alloc_set_opts(&#xA;                null,                           // existing Swr context or NULL&#xA;                AV_CH_LAYOUT_STEREO,            // output channel layout (AV_CH_LAYOUT_*)&#xA;                AV_SAMPLE_FMT_S16,              // output sample format (AV_SAMPLE_FMT_*).&#xA;                44100,                          // output sample rate (frequency in Hz)&#xA;                pAudioCodecCtx.channels(),  // input channel layout (AV_CH_LAYOUT_*)&#xA;                pAudioCodecCtx.sample_fmt(),    // input sample format (AV_SAMPLE_FMT_*).&#xA;                pAudioCodecCtx.sample_rate(),   // input sample rate (frequency in Hz)&#xA;                0,                              // logging level offset&#xA;                null                            // parent logging context, can be NULL&#xA;        );&#xA;        &#xA;        swr_init(audio_swr_ctx);&#xA;        &#xA;        av_samples_fill_arrays(&#xA;                pAudioDecodedFrame.data(),      // audio_data,&#xA;                pAudioDecodedFrame.linesize(),  // linesize&#xA;                audio_data,                     // buf&#xA;                (int)AV_CH_LAYOUT_STEREO,       // nb_channels&#xA;                44100,                          // nb_samples&#xA;                AV_SAMPLE_FMT_S16,              // sample_fmt&#xA;                0                               // align&#xA;        );&#xA;        &#xA;    }&#xA;    &#xA;    // Audio treatment end ---------------------------------------------&#xA;    //==================================================================&#xA;}&#xA;

    &#xA;

    And then when I launch the thread  :

    &#xA;

    private void doPlay() throws Exception{&#xA;    av_init_packet(pPacket);&#xA;&#xA;    // Read frames&#xA;    while (av_read_frame(pFormatCtx, pPacket) >= 0) {&#xA;        if (type != PlayType.AudioOnly &amp;&amp; pPacket.stream_index() == videoStreams.get(0).getStreamIndex()) {&#xA;            // Is this a packet from the video stream?&#xA;            decodeVideo();&#xA;            renewPacket();&#xA;        }&#xA;&#xA;        if (type != PlayType.VideoOnly &amp;&amp; pPacket.stream_index() == audioStreams.get(0).getStreamIndex()) {&#xA;            // Is this a packet from the audio stream?&#xA;            if(pPacket.size() > 0){&#xA;                decodeAudio();&#xA;                renewPacket();&#xA;            }&#xA;        }&#xA;    }&#xA;}&#xA;&#xA;private void renewPacket(){&#xA;    // Free the packet that was allocated by av_read_frame&#xA;    av_packet_unref(pPacket);&#xA;&#xA;    pPacket.data(null);&#xA;    pPacket.size(0);&#xA;    av_init_packet(pPacket);&#xA;}&#xA;

    &#xA;

    And again, this is where I don’t read audio  :

    &#xA;

    private void decodeAudio() throws Exception{&#xA;&#xA;    do {&#xA;        audio_ret = avcodec_send_packet(pAudioCodecCtx, pPacket);&#xA;    } while(audio_ret == AVERROR_EAGAIN());&#xA;    System.out.println("packet sent return value: " &#x2B; audio_ret);&#xA;&#xA;    if(audio_ret == AVERROR_EOF || audio_ret == AVERROR_EINVAL()) {&#xA;        StringBuilder sb = new StringBuilder();&#xA;        Formatter formatter = new Formatter(sb, Locale.US);&#xA;        formatter.format("AVERROR(EAGAIN): %d, AVERROR_EOF: %d, AVERROR(EINVAL): %d\n", AVERROR_EAGAIN(), AVERROR_EOF, AVERROR_EINVAL());&#xA;        formatter.format("Audio frame getting error (%d)!\n", audio_ret);&#xA;        throw new Exception(sb.toString());&#xA;    }&#xA;&#xA;    audio_ret = avcodec_receive_frame(pAudioCodecCtx, pAudioDecodedFrame);&#xA;    System.out.println("frame received return value: " &#x2B; audio_ret);&#xA;&#xA;    audio_data_size = av_get_bytes_per_sample(AV_SAMPLE_FMT_S16);&#xA;&#xA;    if (audio_data_size &lt; 0) {&#xA;        /* This should not occur, checking just for paranoia */&#xA;        throw new Exception("Failed to calculate data size");&#xA;    }&#xA;    &#xA;    double frame_nb = 44100d / pAudioCodecCtx.sample_rate() * pAudioDecodedFrame.nb_samples();&#xA;    long out_count = Math.round(Math.floor(frame_nb));&#xA;&#xA;    int out_samples = swr_convert(&#xA;            audio_swr_ctx,&#xA;            audio_data, &#xA;            (int)out_count,&#xA;            pAudioDecodedFrame.data(0),&#xA;            pAudioDecodedFrame.nb_samples()&#xA;    );&#xA;    &#xA;    if (out_samples &lt; 0) {&#xA;        throw new Exception("AUDIO: Error while converting");&#xA;    }&#xA;    &#xA;    int dst_bufsize = av_samples_get_buffer_size(&#xA;        pAudioDecodedFrame.linesize(), &#xA;        (int)AV_CH_LAYOUT_STEREO,  &#xA;        out_samples,&#xA;        AV_SAMPLE_FMT_S16,&#xA;        1&#xA;    );&#xA;    &#xA;    AudioFormat audioFormat = new AudioFormat(&#xA;            pAudioDecodedFrame.sample_rate(),&#xA;            16,&#xA;            2, &#xA;            true, &#xA;            false&#xA;    );&#xA;    &#xA;    BytePointer bytePointer = pAudioDecodedFrame.data(0);&#xA;    ByteBuffer byteBuffer = bytePointer.asBuffer();&#xA;&#xA;    byte[] bytes = new byte[byteBuffer.remaining()];&#xA;    byteBuffer.get(bytes);&#xA;    &#xA;    try (SourceDataLine sdl = AudioSystem.getSourceDataLine(audioFormat)) {&#xA;        sdl.open(audioFormat);                &#xA;        sdl.start();&#xA;        sdl.write(bytes, 0, bytes.length);&#xA;        sdl.drain();&#xA;        sdl.stop();&#xA;    } catch (LineUnavailableException ex) {&#xA;        Logger.getLogger(AVEntry.class.getName()).log(Level.SEVERE, null, ex);&#xA;    }    &#xA;}&#xA;

    &#xA;

    Do you have an idea  ?

    &#xA;

  • Revision 29188 : 2 options de plus pour personnaliser la page d’activation de la mutu : * ...

    15 juin 2009, par real3t@… — Log

    2 options de plus pour personnaliser la page d’activation de la mutu :
    * ’branding’ : texte libre en HTML
    * ’branding_logo’ => logo (sous forme de HTML)