3 # audiofile.py - audio file handling
5 # Copyright (C) 2003, Xiph.org Foundation
7 # This file is part of positron.
9 # This program is free software; you can redistribute it and/or modify it
10 # under the terms of a BSD-style license (see the COPYING file in the
13 # This program is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY
15 # or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
28 for detect_func
in detect_functions
:
29 metadata
= detect_func(filename
)
35 if metadata
!= None and metadata
["title"] == None:
37 metadata
["title"] = path
.split(filename
)[1]
41 def detect_mp3(filename
):
43 f
= file(filename
, "rb")
45 mp3info
= MP3Info
.MP3Info(f
)
48 info
= { "type" : "mp3",
49 "size" : header
.filesize
,
50 "length" : header
.length
,
51 "title" : mp3info
.title
,
52 "artist" : mp3info
.artist
,
53 "album" : mp3info
.album
,
54 "genre" : mp3info
.genre
,
55 "tracknumber" : mp3info
.track
}
57 # Convert empty string entries to nulls
58 for key
in info
.keys():
74 def detect_oggvorbis(filename
):
76 vf
= ogg
.vorbis
.VorbisFile(filename
)
80 info
= { "type" : "oggvorbis",
81 "size" : os
.stat(filename
).st_size
,
82 "length" : int(vf
.time_total(-1)),
92 actual_keys
.append(tag
.lower())
94 pass # Don't let bad tags stop us
96 for tag
in ("title","artist","album","genre","tracknumber"):
97 if tag
in actual_keys
:
100 # Force these to be single valued
101 if type(value
) == ListType
or type(value
) == TupleType
:
104 # Convert from Unicode to ASCII since the Neuros can't
107 # I will probably burn in i18n hell for this.
108 info
[tag
] = value
.encode('ascii','replace')
112 except ogg
.vorbis
.VorbisError
:
121 def detect_wav(filename
):
122 if filename
[-4:] in ['.wav','.WAV','.Wav']:
123 info
= { "type" : "wav",
124 "size" : os
.stat(filename
).st_size
,
130 "tracknumber" : None}
131 wav_file
=open(filename
)
132 wav_file
.seek(0x04,0)
133 size
= int(struct
.unpack('1i',wav_file
.read(4))[0])
134 wav_file
.seek(0x1c,0)
135 bytes_sec
= int(struct
.unpack('1i',wav_file
.read(4))[0])
137 duration
= size
/bytes_sec
139 info
["length"] = duration
144 # Only put the ogg vorbis detection code in the list if
145 # we have the python module needed.
147 detect_functions
= [detect_mp3
,detect_wav
]
151 detect_functions
.insert(0, detect_oggvorbis
)