Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Inline Mp3player for HTML

// Adds a neat Flash player for evry Mp3 file in a Website.

<script type="text/javascript">
var all = document.getElementsByTagName('a')
for (var i = 0, o; o = all[i]; i++) {
	if(o.href.match(/\.mp3$/i)) {
		var player = document.createElement('span')
		//var tit = o.innerHTML.toString();
		//var tit = ""
		var val = 
			"playerID=1&amp;soundFile="+o.href+"&amp;titles=&amp;artists=&amp;autostart=no&amp;" +
			"loader=0x1030cc&amp;border=0xecf2fa&amp;bg=0xecf2fa&amp;tracker=0xd5e3f4&amp;leftbg=0xd5e3f4&amp;" +
			"rightbg=0xd5e3f4&amp;rightbghover=0x6797d3&amp;lefticon=0x1030cc&amp;righticon=0x1030cc&amp;" + 
			"voltrack=0x6797d3&amp;volslider=0x1030cc"
		player.innerHTML = 
			'<object type="application/x-shockwave-flash" data="/misc/audioplayer.swf" id="player1" height="24" width="479">' +
			'<param name="movie" value="/misc/audioplayer.swf">' +
			'<param name="FlashVars" value='+val+'>' +
			'<param name="quality" value="high">' +
			'<param name="menu" value="false">' +
			'<param name="wmode" value="transparent">' +
			'</object>'
		o.parentNode.insertBefore(player, o)
	}
}
</script>

mp3tom4b

// Not my script But modified it for my needs
// Adds multiple files in a directory together and converts them to a m4b file format.
// You also need to modify it for your needs
// Dependencys: mp3wrap mplayer faac

#!/bin/sh

AUTHOR="Stephen King";
ALBUM="Der Dunkle Turm";
TITLE="5 - Wolfsmond";
YEAR="1997";
PWD="$(pwd)";
I=1;

for F in *
do
  OUT=$F"_$ALBUM - $TITLE.m4b";
  IN=$PWD/$F/"m4b_temp.pcm";
  MPLAYER_IN=$F/$ALBUM" - "$TITLE"_MP3WRAP.mp3";
  mp3wrap $F/"$ALBUM - $TITLE.mp3" $F/*.mp3;
  mplayer -vc null -vo null -ao pcm:nowaveheader:fast:file="$PWD/$F/m4b_temp.pcm" "$MPLAYER_IN";
  faac -R 44100 -B 16 -C 2 -X -w -q 80 --artist "$AUTHOR" --album "$ALBUM" --title "$TITLE" --track "$I" --genre "Spoken Word" --year "$YEAR" -o "$OUT" "$IN";
  I=I+1;
  rm "$PWD/$F/m4b_temp.pcm";
  echo "______________________DONE_______________________________";
done

copycover

// Big thanks to Mark Kretschmann for this fine piece of software
// The file belongs to the great copycover script http://www.kde-apps.org/content/show.php?content=22517
// I needed to modify it a bit so it writes the cover also in the tag of the mp3 file being played.
// To show up covers on mobile devices which read the cover out of the mp3 tag. e.g.: SE C905
// There is also a second script in bash which is basicly an "intro" function for amarok 1.*

#!/usr/bin/env python

############################################################################
# Python-Qt template script for amaroK
# (c) 2005 Mark Kretschmann <markey@web.de>
#
# Depends on: Python 2.2, PyQt
############################################################################
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
############################################################################

import ConfigParser
import os
import Queue
import sys
import threading
import urllib
import commands
import shutil
import subprocess
import mutagen
from mutagen.id3 import APIC



try:
    from qt import *
except:
    os.system( "kdialog --sorry 'CopyCover error: PyQt (Qt bindings for Python) is required for this script.'" )
    raise


debug_prefix = "[AmaroK CopyCover Script]"


class ConfigDialog( QDialog ):
    """ Configuration widget """

    def __init__( self ):
        self.load()
        QDialog.__init__( self )
        self.setWFlags( Qt.WDestructiveClose )
        self.setCaption( "Copy cover script - amaroK" )

        self.lay = QHBoxLayout( self )

        self.vbox = QVBox( self )
        self.lay.addWidget( self.vbox )

        self.hbox1 = QHBox( self.vbox )
        self.hbox1.setMargin(5)
        QLabel( "What filename should I use for album covers ?", self.hbox1 )
        
        self.hbox2 = QHBox( self.vbox )
        self.hbox2.setMargin(5)
        self.albumName = QCheckBox( QString("Use album name"), self.hbox2 )
        
        self.hbox3 = QHBox( self.vbox )
        self.hbox3.setMargin(5)
        QLabel( "Always use this filename : ", self.hbox3 )
        self.filenameEdit = QLineEdit( self.hbox3 )
        self.connect( self.albumName, SIGNAL("toggled(bool)"), self.filenameEdit, SLOT('setDisabled(bool)') )
        self.connect( self.albumName, SIGNAL("toggled(bool)"), self.filenameEdit, SLOT('setDisabled(bool)') )
        if self.filename == "albumname":
            self.filenameEdit.setText("cover.png")
            self.albumName.setChecked(True)
        else:
            self.albumName.setChecked(False)
            self.filenameEdit.setText(self.filename)
            self.filenameEdit.setFocus()

        # Change folder icon
        self.hbox4 = QHBox( self.vbox )
        self.hbox4.setMargin(5)
        self.desktopEntry = QCheckBox( QString("Change folder icon"), self.hbox4 )
        if self.createDE:
            self.desktopEntry.setChecked(True)
        else:
            self.desktopEntry.setChecked(False)
        
        # Remove cover from cache
        self.hbox5 = QHBox( self.vbox )
        self.hbox5.setMargin(5)
        self.removeCoverBox = QCheckBox( QString("Remove from amaroK's cache after copy"), self.hbox5 )
        if self.removeCover:
            self.removeCoverBox.setChecked(True)
        else:
            self.removeCoverBox.setChecked(False)
        
        self.hboxOk = QHBox( self.vbox )
        self.hboxOk.setMargin(5)
        self.ok = QPushButton( self.hboxOk )
        self.ok.setText( "Ok" )
        self.cancel = QPushButton( self.hboxOk )
        self.cancel.setText( "Cancel" )
        self.cancel.setDefault( True )

        self.connect( self.ok,     SIGNAL( "clicked()" ), self.save )
        self.connect( self.cancel, SIGNAL( "clicked()" ), self, SLOT( "reject()" ) )

        self.adjustSize()

    def load( self ):
        """ Loads configuration from file """
        self.config = ConfigParser.ConfigParser()
        try:
            self.config.read( "copycoverrc" )
        except:
            debug( "No config file found, using defaults." )
            self.filename = "cover.png"
            self.createDE = False
            self.removeCover = False
        if self.config.has_option("General", "filename"):
            self.filename = self.config.get("General", "filename")
        else:
            self.filename = "cover.png"
        # desktop entry
        if self.config.has_option("General", "createDesktopEntry"):
            self.createDE = self.config.getboolean("General", "createDesktopEntry")
        else:
            self.createDE = False
        # remove cover
        if self.config.has_option("General", "removeCover"):
            self.removeCover = self.config.getboolean("General", "removeCover")
        else:
            self.removeCover = False

    def save( self ):
        """ Saves configuration to file """
        self.file = open( "copycoverrc", 'w' )
        self.config = ConfigParser.ConfigParser()
        self.config.add_section( "General" )
        if self.albumName.isChecked():
            self.config.set( "General", "filename", "albumname" )
        else:
            filename = str( self.filenameEdit.text() )
            self.config.set( "General", "filename", filename )
        if self.desktopEntry.isChecked():
            self.config.set( "General", "createDesktopEntry", "yes" )
        else:
            self.config.set( "General", "createDesktopEntry", "no" )
        if self.removeCoverBox.isChecked():
            self.config.set( "General", "removeCover", "yes" )
        else:
            self.config.set( "General", "removeCover", "no" )
        self.config.write( self.file )
        self.file.close()
        self.accept()


class CopyCover( QApplication ):
    """ The main application, also sets up the Qt event loop """

    def __init__( self, args ):
        QApplication.__init__( self, args )
        debug( "Started." )

        self.queue = Queue.Queue()
        self.startTimer( 100 )

        # Start separate thread for reading data from stdin
        self.stdinReader = threading.Thread( target = self.readStdin )
        self.stdinReader.start()

        self.readSettings()

    def saveState(self):
        # script is started by amarok, not by KDE's session manager
        sessionmanager.setRestartHint(QSessionManager.RestartNever)

    def readSettings( self ):
        """ Reads settings from configuration file """
        self.filename = "cover.png"
        self.createDE = False
        self.removeCover = False
        config = ConfigParser.ConfigParser()
        try:
            config.read( "copycoverrc" )
        except:
            debug( "No config file found, using defaults." )
        if config.has_option("General", "filename"):
            self.filename = config.get("General", "filename")
        if config.has_option("General", "createDesktopEntry"):
            self.createDE = config.getboolean("General", "createDesktopEntry")
        if config.has_option("General", "removeCover"):
            self.removeCover = config.getboolean("General", "removeCover")


############################################################################
# Stdin-Reader Thread
############################################################################

    def readStdin( self ):
        """ Reads incoming notifications from stdin """

        while True:
            # Read data from stdin. Will block until data arrives.
            line = sys.stdin.readline()

            if line:
                self.queue.put_nowait( line )
            else:
                break


############################################################################
# Notification Handling
############################################################################

    def timerEvent( self, event ):
        """ Polls the notification queue at regular interval """

        if not self.queue.empty():
            string = QString( self.queue.get_nowait() )
            debug( "Received notification: " + str( string ) )

            if string.contains( "configure" ):
                self.configure()

            if string.contains( "engineStateChange: play" ):
                self.engineStatePlay()

            if string.contains( "engineStateChange: idle" ):
                self.engineStateIdle()

            if string.contains( "engineStateChange: pause" ):
                self.engineStatePause()

            if string.contains( "engineStateChange: empty" ):
                self.engineStatePause()

            if string.contains( "trackChange" ):
                self.trackChange()

# Notification callbacks. Implement these functions to react to specific notification
# events from amaroK:

    def configure( self ):
        debug( "configuration" )

        self.dia = ConfigDialog()
        self.dia.show()
        self.connect( self.dia, SIGNAL( "destroyed()" ), self.readSettings )

    def engineStatePlay( self ):
        """ Called when Engine state changes to Play """
        pass

    def engineStateIdle( self ):
        """ Called when Engine state changes to Idle """
        pass

    def engineStatePause( self ):
        """ Called when Engine state changes to Pause """
        pass

    def engineStateEmpty( self ):
        """ Called when Engine state changes to Empty """
        pass

    def trackChange( self ):
        """ Called when a new track starts """
        try:
            self.copyCover()
        except Exception, e:
            message = "The CopyCover amaroK script has run into an unhandled error. " \
                     +"I'm sorry about it, but please tell me about this error, " \
                     +"and help improve the script !\nThe error message was:\n" \
                     +"%s\nPlease look at the end of your ~/.xsession-errors " % e \
                     +"file for error messages too. Thanks."
            os.system("kdialog --title \"AmaroK CopyCover Script\" --sorry \"%s\"" % message)

    def copyCover(self):
        """ Copy a cover to a song's directory """
        cover = commands.getoutput("dcop amarok player coverImage")
        str_cacheFileName = os.path.basename(cover)
        str_cacheDir = os.path.dirname(cover)
        str_baseDir = os.path.dirname(str_cacheDir)
        str_largeDir = os.path.join(str_baseDir, "large")
        str_largeFileName = str_cacheFileName.split("@")[1]
        if os.path.exists(os.path.join(str_largeDir, str_largeFileName)):
            cover = os.path.join(str_largeDir, str_largeFileName)
        if cover.endswith('nocover.png'):
            return
        songDir = self.getAlbumDir()
        if not os.path.exists(songDir):
            debug("ERROR: Invalid dirname: %s" % songDir, level=2)
            return
        filename = self.getCoverName()
        target = os.path.join(songDir, filename)
        target_jpg = os.path.join(songDir, "cover.jpg")
        alreadyThere = False
        """for file in os.listdir(songDir):
            if file.lower()[-4:] in ['.png', '.jpg', '.gif']:
                alreadyThere = True"""
        if not alreadyThere:
            if os.path.exists(cover):
                debug("copy %s to %s" % (cover, target))
                if not os.access(songDir, os.W_OK):
                    debug("ERROR: No write access to %s" % songDir, level=2)
                    return
                shutil.copyfile(cover, target)
		"""os.system("kdialog --title \"AmaroK CopyCover Script\" --sorry \"%s\"" % target)"""
		cmd=["convert", target, target_jpg]
		subprocess.call(cmd)
		imagedata = open(target_jpg, 'rb').read()
                mp3file = commands.getoutput("dcop amarok player path")
                audio = mutagen.File(mp3file)
                audio.tags.add(APIC(3, 'image/jpg', 3, 'Front cover', imagedata))
                audio.tags.save()
                audio.save

                if self.removeCover:
                    os.remove(cover)
                if self.createDE:
                    self.createDesktopEntry()

    def getAlbumDir(self):
        """ Finds the album directory """
        songURL = commands.getoutput("dcop amarok player encodedURL")
        song = urllib.unquote(songURL)
        # A song URL usually looks like file:///path/to/song,
        # but sometimes it can be file:/path/to/song
        song = song.replace("file://", "").replace("file:", "")
        return os.path.dirname(song)

    def getCoverName(self):
        """ Finds the cover name (could be from the album name) """
        if self.filename != "albumname":
            return self.filename
        albumName = commands.getoutput("dcop amarok player album")
        if not albumName:
            return "cover.png"
        illegal_chars = [' ', '/', '"', '*', ':', '<', '>', '?', '\\', '|' ]
        for char in illegal_chars:
            if albumName.count(char) > 0:
                albumName = albumName.replace(char, "")
        return albumName + ".png"

    def createDesktopEntry(self):
        """ Creates the desktop entry to change the folder's icon to the album cover """
        songDir = self.getAlbumDir()
        alreadyThere = False
        for file in os.listdir(songDir):
            if file == ".directory":
                alreadyThere = True
        if not alreadyThere:
            desktopEntry = open(os.path.join(songDir, ".directory"), "w")
            desktopEntry.write("[Desktop Entry]\nIcon=./%s\n" % self.getCoverName())
            desktopEntry.close()
            debug("desktop file created in %s" % songDir)

############################################################################

def debug( message, level=2 ):
    """ Prints debug message to stdout """
    if level == 1: # appears only if lauched from the command line (amarokapp)
        sys.stdout.write(debug_prefix + " " + message + "\n")
    if level >= 2: # appears in ~/.xsession-errors 
        sys.stderr.write(debug_prefix + " " + message + "\n")
    if level >= 3:
        os.system("kdialog --title \"%s\" --sorry \"%s\"" % (debug_prefix, message))

def main( args ):
    app = CopyCover( args )
    app.exec_loop()

if __name__ == "__main__":
    main( sys.argv )


mythtvtomp3

// not my code but slightly modified to fit my needs. I don't know from where I got it. Maybe he/she should give her name in the code...
// Converts a MythTV Radio recording to a Mp3 file so I can heare it on my mobile

#!/bin/bash

###########
#
# Suggested execution format in the job settings for the backend (in general of the backend setup)
# Remember to allow the job to run in the backend general settings too :)
#
# autoaudio.sh %FILE% %STARTTIMEISO% "%TITLE%"
#
###########

OUTPUTDIR="/home/joe/_Multimedia/_Video/_MythTV/Radio"
INPUTDIR="/home/joe/_Multimedia/_Video/_MythTV"
INFILE=$1
ISODATE=`date +%F`
PROGTITLE=$3
STARTDATE=${2:0:10}

# Split
###########
OUTFILE="$OUTPUTDIR/$PROGTITLE - $STARTDATE.mp3"

#transcode mp2 audio to mp3
ffmpeg -i "$INPUTDIR/$INFILE" -acodec libmp3lame -ab 192k -ar 44100 -f mp3 "$OUTFILE"

# Tag
##########
YEAR=`date +%Y`
id3tag --artist="$PROGTITLE" --song="$PROGTITLE - $STARTDATE" --comment="" -y$YEAR -A"Radio" "$OUTFILE"

mp3 file structure flattener

simple bash script to generate Kenwood auto device folders for a large amount of mp3 files

#!/bin/bash
#
# flatten 1.1
# 1.1 change the file list directory to /tmp so we can use readonly source dir
#
# Fred Brooks Jan26 2009 nsaspook
# a bash script to copy mp3 files to a folder structure that the Kenwood
# car audio USB device can understand. Created for DDX812 and others.
# limits files per folder to under 254 with under 254 folders
# per Kenwood specs
#
echo "copy mp3 files into folders for kenwood usb devices"
#
# set source directory to directory where 'flatten' is run
#
mp3filedir=`pwd`
#
# edit variable newmp3filedir to set directory where new file structure
# will be created.
#
newmp3filedir="/media/sdc1/newmp3"
#
# find all mp3 files, send to text file
#
find . -iname '*.mp3' >/tmp/mp3list.txt
#
#read mp3 file list into foo variable
#
k=0
#
cat /tmp/mp3list.txt |
#
# send files to 251 folders at 251 files per folder
#
for ((i=0;i<=250;i+=1)); do
  #
  # check if folder already exists, if yes move on to next folder
  #
  if [ -d "$newmp3filedir/folder$i" ]; then
    continue
  fi
  mkdir $newmp3filedir/folder$i
  for ((j=0;j<=250;j+=1)); do
    read foo
    #
    # check if at EOL in text file or error.
    #
    if [ "$foo" = "" ]; then
      exit
  fi
    #
    # copy mp3 file to new folder
    #
    k=$(($k+1))
    echo "copy file " $foo " to folder"$i" file #"$j" of "$k" files." 
    cp -fp "$foo" $newmp3filedir/folder$i
  done
done

Copying JUST mp3 files, flattening directory structure

// This is a simple find command that copies only mp3 files
// from an iTunes directory; it only copies the files into
// a directory called "mp3_flat"

find /[[yourpath]]/iTunes\ Music -iname "*.mp3" -exec cp {} /[[yourbackuppath]]/mp3_flat/ \;

Copying JUST mp3 files

I wanted to copy just the mp3 files from my iTunes to a backup folder.
First I made a list of all mp3 files, including the full path, in a text file.
Then I went through that file, deleting any files I didn't want backed up.
Then I used rsync to make the backup.

I went through this process to ensure that I only backed up the files I wanted backed up, and no others.

Substitute your paths and file names as appropriate...this was done in the bash shell.

find [[yourpath]]/iTunes\ Music -name "*.mp3" -print >> [[yourpath]]/mp3List.txt

Now do a find/replace on the mp3List.txt file. Replace "[[yourpath]]/iTunes\ Music" with nothing.
rsync -avu --files-from=[[yourpath]]/mp3List.txt [[yourpath]]/iTunes/iTunes\ Music [[yourbackuppath]]/mp3_files

Play sound for certain events in IRSSI

Perl script to allow sounds to be played for different events in IRSSI

Just keep adding handlers to IRSSI's pools pointing to different functions for different events or whatever you want.

use strict;
use vars qw($VERSION %IRSSI);

use Irssi;
$VERSION = '0.0.3';
%IRSSI = (
        authors     => 'Chrelad',
        contact     => 'blah@blah.blah',
        name        => 'alert',
        description => 'Play sounds for different events in IRSSI.',
        url         => 'http://google.com',
        license     => 'GNU General Public License',
        changed     => '$Date: 2007-02-07 12:00:00 +0100 (Thu, 7 Feb 2008) $'
);

#--------------------------------------------------------------------
# Created by Chrelad
# Feb 7, 2008
#--------------------------------------------------------------------

#--------------------------------------------------------------------
# The sound playing function for public message
#--------------------------------------------------------------------

sub pub_msg {
        my ($server,$msg,$nick,$address,$target) = @_;
        `mplayer -quiet ~/file.mp3 > /dev/null`;
}

#--------------------------------------------------------------------
# Irssi::signal_add_last / Irssi::command_bind
#--------------------------------------------------------------------

Irssi::signal_add_last("message public", "pub_msg");
#- end