Skip to content

Feed aggregator

PHP Summit in München

Sebastian Bergmann - Fri, 02/03/2012 - 05:15
spacer

This blog posting is in German as the event it relates to is German-only.
Sorry for the inconvenience.

Bei allen PHP-Themen zählt nichts mehr als die Praxis. Deshalb bieten wir unsere Power-Workshops interaktiv und mit intensivem Praxisbezug an. Über die behandelten Themen entscheiden die Teilnehmer mit ihren konkreten Fragen. Anstelle von Frontalunterricht erleben sie die Entwicklung von neuem Code unmittelbar. Mit Augenzwinkern und Spaß erläutern Sebastian Bergmann, Arne Blankerts und Stefan Priebsch Entwicklungsmethoden und Tools und stellen Trends und Konzepte vor.

Der nächste PHP Summit findet im März in München statt. Und das sind die Workshops:

Update PHP: Neue Features und Technologien nutzen Workshop von Sebastian Bergmann

PHP 5.3 und PHP 5.4 überzeugen im Programmieralltag durch eine Fülle relevanter Vereinfachungen. Lernen Sie die innovativen Features und geschickte Einsatzmöglichkeiten der neuen Versionen kennen. Entdecken Sie das Lösungspotenzial aktueller Technologien aus dem PHP-Umfeld (memcached, ZeroMQ …) für Ihre Fragestellungen.

Weg mit Strubbelcode: identifizieren – verbessern – vermeiden Workshop von Sebastian Bergmann

Früher oder später wird unsauber geschriebener Code zum Ärgernis. Nicht nur für den, der ihn warten muss. Änderungen und Erweiterungen können im Extremfall den Code unwirtschaftlich machen. Lernen Sie schlechten Code durch statische Codeanalyse aufzufinden und in test- und wartbaren Code umzuschreiben. Lernen Sie mithilfe der SOLID-Prinzipien, nachhaltig wartbaren Code zu schreiben.

Best Practices – aus dem Alltag für den Alltag Workshop von Arne Blankerts

Natürlich könnte man das Rad jeden Tag neu erfinden. Meist fehlt dafür die Zeit, Spaß macht es auch nicht und Fehler können sich so immer wieder an denselben Stellen einschleichen. Für die vielen alltäglichen Probleme, die nur geringfügig von schon vorhandenen Lösungen abweichen, gibt es clevere Ansätze, die das Leben leichter machen. In einer komplett vom Auditorium gesteuerten Live Session zeigt der Workshop dafür programmatische Konzepte und lädt zur Diskussion über Tools und klassische Fragestellungen ein.

Auf Fehler sicher vorbereitet sein Workshop von Arne Blankerts

Programme und Webseiten enthalten Fehler. Immer. Sie werden sichtbar, wenn Benutzer falsche, ungültige oder unerwartete Eingaben machen, der Zugriff auf die Datenbank plötzlich unmöglich ist oder die Festplatte überläuft. Um solche und andere Probleme sicher abzufangen, gibt es verschiedene Ansätze, die hier vorgestellt und diskutiert werden. Wie man Exceptions richtig anwendet, warum ein eigener Error Handler hilfreich ist und dass Debugging viel mit Sicherheit zu tun hat, vermittelt der Workshop lebendig und anschaulich.

Objektorientierte Programmierung (OOP) in PHP I: Basiswissen Workshop von Stefan Priebsch

Der Workshop klärt die Frage, was es mit der objektorientierten Programmierung eigentlich auf sich hat. Jenseits der bekannten Standardbeispiele führt er praktisch in die OOP mit PHP ein. Dabei werden neben den Grundlagen und zentralen Prinzipien der OOP interessante Features beispielsweise aus der Standard PHP Library (SPL) vorgestellt und ihr sinnvoller Praxiseinsatz vorgeführt. Neben Faktenwissen wird eine Denkweise vermittelt, die es erlaubt, unnötig komplizierte Ansätze von vornherein zu umgehen.

Objektorientierte Programmierung (OOP) in PHP II: Aufbauwissen Workshop von Stefan Priebsch

Der Workshop zeigt Teilnehmern, die mit den Grundlagen der OOP vertraut sind, fortgeschrittene Techniken wie Dependency Injection, abstrakte Klassen, Interfaces und Best Practices für erfolgreiche OOP. Eine Live-Coding-Session macht den Einsatz der vorgestellten Techniken in der Praxis erfahrbar. Außer Faktenwissen zeigt der Workshop, dass gute Lösungen einfache Lösungen sind: Einfache Objekte sind leichter wieder zu verwenden und vermeiden Fehler.

PHP-Anwendungen testen: Basiswissen Workshop von Sebastian Bergmann

Der Workshop vermittelt grundlegende Kenntnisse und Fähigkeiten im Einsatz von PHPUnit bei Unit Tests, Datenbank-Interaktionstests, Edge-to-Edge- Tests und End-to-End-Tests. Sie lernen alles, was Sie über das Schreiben, Ausführen und Organisieren von Unit Tests mit PHPUnit beherrschen müssen.

PHP-Anwendungen testen: Aufbauwissen Workshop von Sebastian Bergmann

PHPUnit clever einsetzen: Die Teilnehmer lernen die besten Praktiken beim Einsatz von PHPUnit und erprobte Strategien bei der Einführung von Testmaßnahmen an vorhandener Software kennen. Anhand zahlreicher Beispiele entwickeln Sie einen Blick für schlechte Tests und lernen, sie zu verbessern, schwer testbaren Code zu identifizieren und Legacy-Code Schritt für Schritt testbar zu machen.

Geheimtipp XML: Die smarte Art der Anwendung Workshop von Arne Blankerts

XML ist das Standardformat für den Datenaustausch im Web und verbirgt sich in vielen, für Endanwender oft nicht sichtbaren Dateiformaten (z. B. aktuelle MS-Office-Versionen) und Formen. Der Workshop zeigt, dass XML richtig Spaß machen kann, wenn die übermittelten Daten validiert werden und der Zugriff mit effiziente APIs erfolgt. In der Live Session erweitern wir das DOM-API von PHP um eigene Methoden und unterstützen die Lokalisierung durch PHP. Eigene XSD Schemas zur Validierung werden definiert und der Einsatz von XPath als Abfragesprache vorgeführt. Vermittelt wird auch der Einblick in eine wirklich effektive Fehlerbehandlung.

Neu: Tuning für Web-Anwendungen Workshop von Arne Blankerts

Wer einen ungeschickten Weg zur Lösung beschreitet, handelt sich Probleme ein, die er gar nicht haben möchte. In der Regel geht das zulasten des Tempos und der Skalierbarkeit. Wie man solche Schwachpunkte in gängigen Aufbauten und Architekturen vorab erkennt und durch bessere Konzepte von vornherein vermeiden kann, zeigt dieser Workshop an zahlreichen Praxisbeispielen. Eigene Denk- und Herangehensweisen können überprüft und modifiziert werden.

Entwurfsmuster I: Die wichtigsten Standards Workshop von Stefan Priebsch

Warum das Rad jedes Mal neu erfinden? Die Teilnehmer lernen in diesem Workshop wichtige Entwurfsmuster kennen, die sich in PHP-Webanwendungen besonders bewährt haben. Häufig in der Praxis auftretende Schwierigkeiten werden vorgeführt und Lösungen werden live programmiert. Vor- und Nachteile sowie Einsatzmöglichkeiten und typische Fehler bei der Anwendung von Standardmustern werden ausführlich erläutert und diskutiert.

Entwurfsmuster II: Integration anspruchsvoller Patterns Workshop von Stefan Priebsch

Der Workshop behandelt Themenstellungen wie temporale Patterns, das Speichern von Objekten in relationale und NoSQL-Datenbanken oder Enterprise Integration Patterns mit Schwerpunkten, die von den Teilnehmern frei festgelegt werden. Eine Reihe typischer Probleme wird vorgeführt und analysiert. Die zu ihrer Lösung eingesetzten (wenig bekannten) Entwurfsmuster vermitteln den Teilnehmern fortgeschrittene Kenntnisse, die im Alltag wertvoll sind.

Moderne Versionskontrolle mit Git Workshop von Sebastian Bergmann

Git ist ein mächtiges Versionsverwaltungssystem, mit dem Sie alle Bestandteile Ihrer Software durch alle Änderungen und Versionen zuverlässig verfolgen können. Damit schaffen Sie die Grundlage für die kontinuierliche Integration der Software. Der Workshop vermittelt Grundlagen für den Einsatz von Git, Best Practices und Prozesse für Entwicklung, Release-Management und Deployment, die Ihre Teamarbeit spürbar effektiver machen.

Kontinuierliche Integration mit Jenkins Workshop von Sebastian Bergmann

Wer die Qualität seiner Software während der Entwicklung und im Betrieb messen und kontrollieren will, profitiert vom Einrichten einer Umgebung, in der PHP-Projekte kontinuierlich integriert werden können. Mit der Kombination dynamischer und statischer Testverfahren automatisieren Sie wiederkehrende Aufgaben, sind über die Softwarequalität auf dem Laufenden und minimieren Projektrisiken erfolgreich. Der Workshop vermittelt die Grundlagen der kontinuierlichen Integration und Inspektion von PHP-Software. Sie üben Installation, Konfiguration und Betrieb von Jenkins für PHP-Projekte.

Am besten mit dem Schlimmsten rechnen! Workshop von Arne Blankerts

In Zeiten ständiger Einbruchsversuche durch gelangweilte Anwender ergibt es Sinn, wirklich immer mit Angriffen aus dem Internet zu rechnen. Auch vermeintlich sichere Strukturen bieten versierten Hackern oft keinen nennenswerten Widerstand. Verantwortungsbewusste Entwickler müssen wissen, wie man der eigenen Anwendung oder Infrastruktur schaden könnte. Der Workshop vermittelt grundlegende Zusammenhänge und zeigt in einer Live Session, was Begriffe wie XSS, CSRF oder SQL-Injection bedeuten, wie man Angreifern das Leben schwer macht und wirksame Lösungen implementiert.

Attacke! Was Angriffe im Web erfolgreich macht Workshop von Arne Blankerts

Anwendungen sind im Internet permanent Angreifern ausgesetzt. Im Workshop wechseln die Teilnehmer die Seiten und greifen selbst eine Demo-Blackbox-Anwendung an. Sie lernen, wie Angreifer Informationen sammeln, Sicherheitslücken ausnutzen und Server übernehmen. Vermittelt werden Methoden, um Lücken zu finden, sie zu schließen und Angriffe abzufangen. Der abschließende Blick in den Quellcode sensibilisiert für Schwachstellen und zeigt, wie man sie behebt.

Framework: Basics in drei Stunden Workshop von Stefan Priebsch

Grundlegende Fragen nach der Struktur einer Webanwendung und dem Schreiben von Code, der test-, wart- und erweiterbar ist, werden an einem praktischen Beispiel beantwortet. Wichtige Entwurfsmuster und Best Practices werden vorgeführt. Feedback und Fragen der Teilnehmenden steuern den Verlauf der Session. Ziel ist ein besseres Verständnis für die wesentlichen Konzepte von Frameworks.

Warum der Turm in Pisa schief steht Workshop von Stefan Priebsch

Nichtfunktionale Aspekte werden in ihrer Bedeutung für technische Entscheidungen oft unterschätzt oder ganz übersehen. Je komplexer die Fragestellungen desto wahrscheinlicher ist es, dass aus diesem Wegschauen Probleme resultieren, die später nicht leicht einzufangen sind. Wer sich vor der Entwicklung Gedanken zur Architektur macht, löst heute Probleme von morgen. Der Workshop zeigt Architekturmuster für Webanwendungen und geht auf aktuelle Trends wie Distributed Caching, Message Queues und NoSQL ein. Es werden erprobte Bausteine vorgestellt, mit denen hochperformante und skalierbare Webanwendungen in PHP entwickelt werden können.

Der PHP Summit bietet effizientes Lernen in entspannter Atmosphäre. Profitieren Sie von dieser einzigartig intensiven Form der Informationsvermittlung mit einem unschlagbaren Preis-Leistungs-Verhältnis und reservieren Sie sich Ihren Platz noch heute!

Categories: Blogs

Jeremy Cook's Blog: Implementing the ArrayAccess Interface

PHPDeveloper.org - Thu, 02/02/2012 - 20:56

Jeremy Cook is back with the next part of his series looking at the handy features PHP's SPL provides. In this new post he looks at the ArrayAccess interface and how it can make your data more accessible to PHP's own array handing functions.

ArrayAccess allows you to treat an object that implements it as if it is an array for the purposes of setting, unsetting and retrieving data from it. Please note the emphasis in the last sentence! ArrayAccess does not make an object behave like an array in any other way. If you pass an object that implements ArrayAccess to a PHP array function such as in_array() you'll still get an error. This will become a little clearer with some of the examples below.

He shows what you'll need to use this interface in your class - implementing the interface and defining a set of four methods to get/set and check for the value in your array. He includes a practical example of pulling data back from an API and wrapping it in a class to make accessing it simpler (also implementing the Countable interface as well, see the previous post for more on that). Code is include to illustrate how it can be used.

Categories: Blogs

Leaseweb Labs Blog: POC: Flexible PHP Output Caching

PHPDeveloper.org - Thu, 02/02/2012 - 19:10

On the Leaseweb Labs blog there's a recent post looking at using the POC framework to work with flexible output caching. The tool makes it easy to create a new object and push cache content into it, automatically caching the data to sources like the file system, a Redis instance or a MongoDB database.

Last year at the Symfony conference in Paris I have heard a really good quote: "There are only two hard things in Computer Science: cache invalidation and naming things" - Phil Karlton. I agree with it and it gave me a boost to keep evolving the concept.

He includes an introduction to the caching features of the framework complete with sample code showing first how to cache to the default file system and a more complex example that uses unique caches and page blacklists. Other features planned for the caching tool include edge-side includes, using Twig for templating and statistics recorded to a database.

Categories: Blogs

LearnComputer.com: PHP Training: Online vs. Classroom

PHPDeveloper.org - Thu, 02/02/2012 - 18:22

On the LearnComputer.com site there's a new post comparing the benefits/downfalls of online versus classroom learning of PHP development. They list a few advantages and disadvantages of each.

There can be many factors in the decision to learn PHP online or to take a class in-person, and for some, this can be a difficult decision to make. This article discusses the pros and cons of each method of PHP training to help you find the learning method that is going to suit your needs best. PHP isn't a new programming language, and there is a wealth of information on it on the web for every level of proficiency. The question is whether these resources alone are sufficient to get you up-and-running with PHP quickly.

For the "online" section advantages include flexible schedules and more up to date content. The disadvantages are things like a prerequisite knowledge of using computers/the training software and that the instructor might only have "set hours" to answer questions and offer help. The "classroom" option advantages include the motivation of a regular meeting time and fewer technology hurdles to overcome. Disadvantages include the need for a time/in-person commitment and that the focus might be higher level than needed to appeal to a more mass audience.

Categories: Blogs

AndroidHive: Android Login and Registration with PHP, MySQL and SQLite

PHPDeveloper.org - Thu, 02/02/2012 - 17:41

On the AndroidHive site there's a recent tutorial (plus screencast) about combining PHP, MySQL and SQLite to act as the backend authorization for your Android application.

In my previous article Android Login and Registration Screen Design i explained designing the login and registration interfaces, but it has no functionality. In this tutorial i am explaining how to build complete login and registration system in android using PHP, MySQL and SQLite. Also this tutorial covers how to build simple API using PHP and MySQL.

The tutorial walks you through each step of the process:

  • Creating MySQL Database and Tables
  • Building PHP API Classes
  • Starting Android Project
  • Making the JSON Parser, SQLite Database Handler and User Functions Classes
  • Designing the Screens
  • Switching between Activities
  • Finally Updating AndroidManifest.xml

If you want to get started quickly, you can just download the final result and go.

Categories: Blogs

Script-Tutorials.com: Form Validation with Javascript and PHP

PHPDeveloper.org - Thu, 02/02/2012 - 16:07

On the Script-Tutorials.com site today there's a new tutorial about form validation using a combination of jQuery on the frontend and PHP on the backend.

In this tutorial, I will show you how to create an attractive, pleasant to look form for your website and then I will explain you how to dynamically validate them using Javascript. We'll also cover server-side validation with PHP to make everything 100% safe. This tutorial will help you to add more functionality to your forms which leads to better user experience and better quality of your website.

His sample form (name, password, email and gender) is made from some pretty simple HTML markup. The real trick comes with the jQuery validation on each field handled in an onKeyUp. Included are both a "password strength" method and an email validation method to check the format of the address. Errored fields have their background color changed to indicate that they've failed and some basic validation (length, password match, etc.) are also included. The PHP does much of the same validation once the form is posted and returns any error messages that might have come up.

You can download the code or try out a live demo to see the scripts together in action.

Categories: Blogs

PHPMaster.com: Where on Earth are You?

PHPDeveloper.org - Thu, 02/02/2012 - 15:52

In PHPMaster.com's latest tutorial Lukas White introduces you to using the Yahoo "Placemaker" web service to geographically locate a place from a free-form text string. The results include "place details" like the type of the location, latitude, longitude and how confident they are in their match.

The challenge then is to do two things: work out what place you could be talking about, disambiguate if necessary, and then identify exactly where on Earth that is. That's what I'll show you how to do in this article; by using a freely available web service, we'll write a simple program to ask users where they are (and ask them to clarify if necessary) before identifying their responses in concrete terms.

He shows how to make a request to the Placemaker web service, passing it a string coming from the user, to be located. The POST request contains a few pieces of data including an application ID , your desired output type and the language you're using for the input. His example code uses curl to make the request and handles it (the XML response at least) with a call to simplexml_load_string.

Categories: Blogs

Site News: Blast from the Past - One Year Ago in PHP

PHPDeveloper.org - Thu, 02/02/2012 - 14:00
Here's what was popular in the PHP community one year ago today:
  • Chris Hartjes' Blog: Book Review: PHP 5 Social Networking
  • Rob Allen's Blog: Zend Framework 2 in Action
  • Mike van Riel's Blog: Introducing: DocBlox
  • SocialDevelopers.net: Facebook and the Zend Framework - Part 1: br Authentication
  • Binpress.com: Web Developer Programming Contest
  • Matthew Weier O'Phinney's Blog: Why PHP Namespaces Matter
  • Michael Feichtinger's Blog: PHP5 WebSocket Example - A Simple Chat
  • Greepit.com: Behavior Driven Development Framework for PHP: Behat
  • CodeIgniter.com: CodeIgniter 2.0.0 Released
  • Steve Francia's Blog: On Symfony2
  • Joshua Thijssen's Blog: Password hashing and salting
  • Volker Dusch's Blog: Setting up Jenkins for PHP Projects
  • InfoWorld: InfoWorld review: Fabulous PHP frameworks
  • Strattonbrazil's Blog: php to python: Why PHP is now dead to me
  • Gonzalo Ayuso's Blog: Function decorators in PHP with PHPDoc and Annotations
Categories: Blogs

FFmpeg: A beginners guide – part 2

<code:diesel /> - Thu, 02/02/2012 - 11:38

Continuing the last post on FFmpeg, here we will discusses various fundamental tasks you can accomplish with the audio stream in FFmpeg.

2.1.1 Introduction to Transcoding

One of the basic tasks you can perform on an audio track in FFmpeg is to convert it into another format. This process known as Transcoding, is the direct digital-to-digital conversion of one stream encoding to another, whether video or audio. Transcoding is usually done in cases where a target device – media player such as iPod, iPAD, DVD players or a software application, does not support the format or has limited storage capacity that requires a condensed file size. Transcoding can also be used to convert an incompatible or obsolete format to a better-supported format.

Transcoding is generally a “lossy process” – a data encoding method which compresses data by discarding (losing) some of it to minimize the amount of data that need to be stored in a file; however, transcoding can also be “lossless” if the input is losslessly compressed and the output is either losslessly compressed or stored in a uncompressed state. Although compression can reduce file size considerably, repeatedly performing transcoding on a single file using lossy compression can create a ‘generation loss’ – a reduction in the quality of the audio when copying, which would cause further reduction in quality on making a copy of the copy. So you need to keep this in mind while repeatedly transcoding between various formats.

Although I could not show you here the difference between an original and lossy audio compression (due to the limitation of the media of course), the following shows an example of a lossy compression in an image. The original JPG image is on the left and a lossy image of the same after repeated compression is shown on the right. As we lose precious information forever during compression, we cannot get back the original image using the compressed image.

spacer

2.1.2 Audio compression

Audio compression is a form of data compression designed to reduce the transmission bandwidth and storage requirement of a digital audio stream. Audio compression algorithms are implemented in software as audio codec’s, – which is a software program or library capable of encoding/decoding a digital audio stream.

Audio compression is either lossy or lossless as discussed earlier. Lossless audio compression produces a version of digital audio that can be decoded to an exact digital duplicate of the original audio stream. This is in contrast to the irreversible changes upon playback from lossy compression techniques such as Vorbis and MP3.

The whole idea behind audio compression in FFmpeg is to lower the audio bitrate (96kbps, 128kbps, 192 kbps etc.), this effectively also reduces the fidelity or quality of the audio. So you want to keep in mind that, a high bitrate audio file confirms a better sound quality, so by lowering its bitrate you are actually degrading the quality.
For normal computer use, the 128kbs rate produces a quality equal to that of an audio CD. But in the case of an MP3 use, it is necessary to use a 256kbs bitrate to reach an identical result to that of the CD quality sound.

2.1.3 Getting your audio file ready

Now that we have gone through a short introduction to compression, we will now work on the process of transcoding audio files.

To run the example commands in this section, you will need an audio file in a .wav or an .mp3 format. You can get hold of a wav file by ripping an audio track from a music CD or downloading an mp3 file from the Internet. Call the resulting file ‘myaudio.mp3’. For this section I used the ‘Solo Piano 7’ Opening file from www.archive.org/details/solo-piano-7.

Next, we will get ffmpeg to identify the file. This will tell us the various details of the audio file. The simple way to get this information is to just tell ffmpeg to use it for input. For this we need to use the –i option. Enter the following command at your prompt.

ffmpeg  -i  myaudio.mp3

The exact output on my PC is shown below; which may differ from yours depending on the version of ffmpeg you are using.

D:\ffmpeg>ffmpeg -i myaudio.mp3
ffmpeg version N-31100-g9251942, Copyright (c) 2000-2011 the FFmpeg developers
Input #0, mp3, from ‘myaudio.mp3′:
Metadata:
album : solo piano 7
artist : Torley
album_artist : Torley
composer : Torley
genre : Piano
track : 001/176
title : 001 – Openings
date : 2008
Duration: 00:01:39.50, start: 0.000000, bitrate: 193 kb/s
Stream #0.0: Audio: mp3, 44100 Hz, stereo, s16, 192 kb/s
At least one output file must be specified

There is a lot of information we can gather from the output – the track is
1 minute 39.50 seconds long, the bitrate is 193kb/s, the audio is encoded in mp3 format at 44100Hz (44.1KHz) and has two channels (stereo). All this information will come in handy during a transcoding process.

2.1.4 Transcoding to a different format

Let us now convert the downloaded file to a simple wav format. Notice that we have not specified any format option or flag, just the complete output filename. FFmpeg automatically guesses which encoders to use by noticing the format of the input and output files, this can be a big help if you keep forgetting the option name or are just being lazy. If you are not going to specify the encoder format, make sure you mention the full filename, along with the appropriate format extension.

ffmpeg  -i  myaudio.mp3  myaudio.wav

The output of the command is shown below.

ffmpeg version N-31100-g9251942, Copyright (c) 2000-2011 the FFmpeg developers
Input #0, mp3, from ‘myaudio.mp3′:
Metadata:
album : solo piano 7
artist : Torley
album_artist : Torley
composer : Torley
genre : Piano
track : 001/176
title : 001 – Openings
date : 2008
Duration: 00:01:39.50, start: 0.000000, bitrate: 193 kb/s
Stream #0.0: Audio: mp3, 44100 Hz, stereo, s16, 192 kb/s
File ‘myaudio.wav’ already exists. Overwrite ? [y/N] y
Output #0, wav, to ‘myaudio.wav’:
Metadata:
album : solo piano 7
artist : Torley
album_artist : Torley
composer : Torley
genre : Piano
track : 001/176
title : 001 – Openings
date : 2008
encoder : Lavf53.4.0
Stream #0.0: Audio: pcm_s16le, 44100 Hz, stereo, s16, 1411 kb/s
Stream mapping:
Stream #0.0 -> #0.0
Press [q] to stop, [?] for help
size= 17141kB time=00:01:39.50 bitrate=1411.2kbits/s
video:0kB audio:17141kB global headers:0kB muxing overhead 0.000251%

Notice how large the resulting wav file is (17 Mb) as compared to the original mp3 format (2.1 Mb). This being for the reason that the wav file is not compressed like its mp3 counterpart. Incidentally, the audio format of the wav is Pulse-code modulation (PCM), technically PCM signed 16 bit little-endian format.

As you can see from the screenshot above the output of an ffmpeg command is quite large, so from here on I’ll just specify the command and do away with the output screen unless it is required for explanation.

2.1.5 Changing the bitrate of the audio

As we learned in Chapter 1, bitrates control the file size and the quality of an audio or video stream. Lowering the bitrate will result not only in a reduced file size but also diminish the quality of the final output. This can be required if you have a high quality audio recording and need to lower the quality for a reduced file size to stream over the Web. For example the following command will set the bitrate of the mp3 file to 64kb/s. This uses the –ab option to the job.

-ab

ffmpeg  -i  myaudio.mp3  -ab 64k  out.mp3

The higher the value the better is the audio quality. This is one of the important factors responsible for the audio quality. But that doesn’t mean you can make a poor audio file sound better by increasing its bitrate. The resultant file will just be of bigger size.

Another example – to transcode an mp3 file to an AAC format, with a bitrate of 128K, we can use the following.

ffmpeg  -i  myaudio.mp3  -ab 128k  myaudio.aac

As we saw earlier the original audio track has 2 channels (stereo). Many times it is not necessary to have 2 channels, like in a speech recording, where its really doesn’t matter.. In such cases you can further reduce the file size by setting the audio channels to mono or ‘1’. For output streams it is set by default to the number of input audio channels.

-ac

ffmpeg  -i  myaudio.mp3  -ac 1 out.mp3

Note that once you convert a stereo channel to a mono, you cannot convert it back to a stereo channel audio. That information is lost forever. The same thing happens with bitrates. Once you reduce a bitrate of an audio file, you cannot just increase the bitrate back again to get the original quality. That information is already gone. So as a precaution, never work with your original media files. Make a copy of the original and work with the copy.

The other important audio option is –acodec. This option lets you choose the type of audio codec you want to use. e.g. if you are using ffmpeg on a mp3 file, then it will need the audio codec libmp3lame. You can specify it using -acodec libmp3lame. Although, by default, ffmpeg takes care of the codecs you need (by guessing it from the output file format) but if you need anything different, then go for this option. FFmpeg uses a default encoder for each audio stream, using the output file extension to guess the encoder to use. This option lets you force FFmpeg to use a specific audio encoder rather than the default. The following for example will extract the audio stream from a .flv video and save it as an .mp3 file using the libmp3lame encoder.

-acodec

ffmpeg  -i  myvideo.flv   -acodec  libmp3lame  myaudio.mp3

Sometime you FFmpeg may be unable to correctly decode the input file, giving the error something like the following.

Error while decoding stream #0.0

In such cases you can force FFmpeg to use a particular decoder to decode the input file. The following example will force FFmpeg to use the mp3 codec toe decode the input file audio.

ffmpeg  -acodec  libmp3lame  -i  myvideo.flv    myaudio.mp3

Note that the –acodec option comes before the –i option when we want the codec to apply to the input stream and comes after the –i option when we want the codec to apply to the output stream. To see what codecs are available on your system, issue the following command.

ffmpeg  -codecs

Sometimes you may want to completely disable the audio recording for which we can use the –an option. This can be used to strip out an audio stream from a video file. When you use this option, all the other audio related attributes are cancelled out, which is fine, as they would not matter without the audio. So for example you are want to disable the audio from a video file and only copy the video stream, you can use the following.

ffmpeg  -i  myvideo.flv  -an out.flv

Another important option is –ar, the audio sampling frequency. This lets you set the maximum sampling frequency of the audio stream. Audio sampling was discussed in Chapter 1. You can use the option to reduce the sampling frequency to a lower value to reduce file storage or Internet bandwidth capacity. The default value is set at 44100Hz. The value is given in Hz. So the following will resample the input audio to 11025Hz with a single channel (mono).

-ar

ffmpeg  -i  myaudio.mp3  -ar 11025  -ac 1 myaudio.mp3

Note that once you have reduced the sampling frequency some of the audio data is lost. You cannot again resample it to a higher value and expect increase in the audio quality.

2.1.6 Audio grabbing

Until now we have looked into how to transform existing audio stream into other formats. FFmpeg can also grab audio from external devices such as a microphone. This can be useful if you need to record from your desktop microphone or create a screencast. Note that the following command will not work on a Windows machine. You need to have a Linux machine to correctly grab the mic audio. Enter the following command at your Linux prompt.

ffmpeg  -f oss  -i  /dev/dsp  ./audio.wav

This will start recording the input audio from the mic to the ‘audio.wav’ file. Once started you will need to press ‘q’ to stop the recording. We will now look into the various options given above.
The option –f denotes the format to be used for the input stream. There are various formats FFmpeg supports; you can find the complete list by issuing the following command.

ffmpeg  -formats

Here we are using the ‘oss’ format, which stands for Open Sound System input device. The Open Sound System (OSS) is an interface for making and capturing sound in Unix or Unix-like operating systems. In the Linux kernel, there have historically been two uniform sound APIs. One is OSS; the other is ALSA (Advanced Linux Sound Architecture). ALSA is available for Linux only.

The device ‘/dev/dsp’ is the default audio input device in the Linux system. It’s connected to the main speakers and the primary recording source such as a microphone. The system administrator can set /dev/dsp to be a symbolic link to the desired default device.

The ‘audio.wav’ file is where the recorded audio will be saved.
Another example – the following will record the mic audio to the file ‘rec.flac’ in the current directory, this is a flac format file.

ffmpeg  -f alsa  -ar 48000  -i front  ./rec.flac
2.2 Some popular audio formats

.AAC Advanced Audio Coding File – declared the new audio-file standard in 1997, designed to replace its predecessor, MP3. It provides better quality at lower bit rates, and its Apple’s standard iTunes and iPod audio format.

.AIF(F) Audio Interchange File Format – developed by Electronic Arts and Apple back in the ’80s. AIFF files contain uncompressed audio, resulting in large file sizes.

.m4a Apple Lossless – This file format uses lossless compressions for digital music.

.MP3 MPEG Layer 3 – the most popular digital-audio music format, designed by a team of European engineers in 1991 to conserve the quality of a song while storing it in a small, compact file.

.OGG Ogg Vorbis – one of the most popular license-free, open-source audio-compression formats. It’s efficient for streaming and compression because it creates smaller files than MP3 while maintaining audio quality.

.RA(M) Real Audio Media – developed by RealNetworks in 1995. It has a wide variety of uses, from videos to music, but is mainly used for streaming audio such as that from Internet radio stations.

.WAV Windows WAVE – IBM and Microsoft-developed format popular audio format among PC computer users; it can hold both compressed and uncompressed audio.

.WMA Windows Media Audio - designed by Microsoft to be an MP3 competitor, but with the introduction of iTunes and iPods, it’s fallen far behind MP3 in popularity.

2.3 Audio processing recipes

MP3 to AAC High Quality Stereo

ffmpeg -i in.mp3  -acodec aac -ac 2 -ar 48000 -ab 192k out.aac

MP3 to AAC High Quality 5.1

ffmpeg -i in.mp3  -acodec aac -ac 6 -ar 48000 -ab 448k out.aac

Convert to low quality mp3 to preserve storage

ffmpeg  -i in.mp3 -ab 64K out.mp3

MP3 to Vorbis OGG (can be played in HTML 5)

ffmpeg  -i in.mp3 -acodec vorbis -aq 50 out.ogg

In the next post in the series we will look into various video processing tasks.

Subscribe now to get the next post update.

spacer
Categories: Blogs

FFmpeg: A beginners guide – part 1

<code:diesel /> - Thu, 02/02/2012 - 05:44

The idea for this posts arose from my frustration on not finding any organized documentation for learning FFmpeg. Thus, my aim in writing this series has been to provide newbie learners to quickly get up-and-running with FFmpeg.

1.1.1 What is FFmpeg?

FFmpeg is a command-line tool for *nix and Windows systems that, in its simplest form, provide a facility to decode and an encode media files. With the proliferation of video on the Internet and in our daily lives, users need the ability to transcode (convert) audio and video files from one format to another. For example, a user might have downloaded a video from YouTube and need to convent it to a format playable on an iPod or other media device.

Besides this obvious use, FFmpeg is also capable of a few other fundamental manipulations on the audio and video data. These manipulations include changing the sample rate of the audio and advancing or delaying it with respect to the video, reducing the size of the media file. They also include changing the frame rate of the resulting video, cropping it, resizing it, placing bars left and right and/or top and bottom in order to pad it when necessary, or changing the aspect ratio of the picture. Furthermore, ffmpeg allows importing audio and video from different sources such as a microphone.

The main components of FFmpeg are libavcodec, an audio/video codec library, libavformat, an audio/video container mux/demux library, and the ffmpeg command line program for passing various transcoding options to the main program.

The FFmpeg project was started by Fabrice Bellard, and has been maintained by Michael Niedermayer since 2004. The name of the project comes from the MPEG video standards group, together with “FF” for “fast forward”. On March 13, 2011 a group of FFmpeg developers decided to fork the project under the name Libav (libav.org/) due to some project management related issues.

FFmpeg is used by many open source and proprietary projects, including ffmpeg2theora, VLC, MPlayer, HandBrake, Blender, Google Chrome, and various others.

1.1.2 Components of FFmpeg

FFmpeg is made of the following main components.

Programs
ffmpeg – a command line tool to convert multimedia files between formats.
ffserver – a multimedia streaming server for live broadcasts.

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.