How to Check If a File Is Mp3 or Image File

How can I check if a file is mp3 or image file?

You can identify image files using getimagesize.

To find out more about MP3 and other audio/video files, I have been recommended php-mp4info getID3().

Check if a file type is a media file?

For this purpose you need to get internet media type for file, split it by / character and check if it starts with audio,video,image.

Here is a sample code:

import mimetypes
mimetypes.init()

mimestart = mimetypes.guess_type("test.mp3")[0]

if mimestart != None:
mimestart = mimestart.split('/')[0]

if mimestart in ['audio', 'video', 'image']:
print("media types")

NOTE: This method assume the file type by its extension and don't open the actual file, it is based only on the file extension.

Creating a module

If you want to create a module that checks if the file is a media file you need to call the init function at the start of the module.

Here is an example of how to create the module:

ismediafile.py

import mimetypes
mimetypes.init()

def isMediaFile(fileName):
mimestart = mimetypes.guess_type(fileName)[0]

if mimestart != None:
mimestart = mimestart.split('/')[0]

if mimestart in ['audio', 'video', 'image']:
return True

return False

and there how to use it:

main.py

from ismediafile import isMediaFile

if __name__ == "__main__":
if isMediaFile("test.mp3"):
print("Media file")
else:
print("not media file")

How to detect if file is mp3 using Apache tika TypeDetector?

Taken from the Apache Tika examples:

File file = new File("/path/to/file.mp3");

Tika tika = new Tika();
String type = tika.detect(file);
System.out.println(file + " : " + type);

That will detect on both the file contents and the file name. For an MP3 file, you'll get back audio/mpeg

How can I check if a file is mp3 or image file?

You can identify image files using getimagesize.

To find out more about MP3 and other audio/video files, I have been recommended php-mp4info getID3().

Check if file is a media file in C#

It depends how robust you want it to be.

The simplest way to do it is to check the extension, like this:

static string[] mediaExtensions = {
".PNG", ".JPG", ".JPEG", ".BMP", ".GIF", //etc
".WAV", ".MID", ".MIDI", ".WMA", ".MP3", ".OGG", ".RMA", //etc
".AVI", ".MP4", ".DIVX", ".WMV", //etc
};

static bool IsMediaFile(string path) {
return -1 != Array.IndexOf(mediaExtensions, Path.GetExtension(path).ToUpperInvariant());
}

EDIT: For those who really want LINQ, here it is:

return mediaExtensions.Contains(Path.GetExtension(path), StringComparer.OrdinalIgnoreCase);

Note that a file's extension is not a reliable indicator of its content; anyone can rename a file and change its extension.

If you don't have the extension, or if you don't trust it, you can read the beginning of the file and see if it matches file signatures for common media formats.

check if the file is audio file in PHP

All the audio files format has "audio/" common in MIME Type. So, we can check the $_FILES['file']['mime_type'] and apply a preg_match() to check if "audio/" exists in this mime type or not.

Detect if a file is an MP3 file?

Detecting if a file is an MP3 is more complicated than searching for a fixed pattern in the file.

Some concepts

(See http://www.codeproject.com/Articles/8295/MPEG-Audio-Frame-Header for details)

  • MP3 file consists of a series of frames and each frame has a header at the beginning.
  • Header starts at a byte boundary with an 11-bit sync word, which is all 1s. Hence the sync word is either 0xFFE or 0XFFF.
  • Length of each frame is calculated based on the header parameters.

Algorithm to determine if a file is MP3 or not

  • Search for the sync word in the file (0xFFF or 0xFFE).
  • Parse the header parameters.
  • Determine the frame length using the header parameters.
  • Seek to the next frame using the frame length.
  • If you find another sync word after seeking, then the file is mostly an MP3 file.
  • To be sure, repeat the process to find N consecutive MP3 frames. N can be increased for a better hit-rate.

How to differentiate a MP3,MP4 file?

To determine it's a mp3, look at the first two or three bytes of the file. If it's 49 44 33 or ff fb, you have a mp3.

And a signature of ftyp may indicate a .mp4 file.

Here's some Swift code I worked up for this purpose:

import Foundation

var c = 0;
for arg in Process.arguments {
print("argument \(c) is: \(arg)")
c++
}

let pathToFile = Process.arguments[1]

do {
let fileData = try NSData.init(contentsOfFile: pathToFile, options: NSDataReadingOptions.DataReadingMappedIfSafe)

if fileData.length > 0
{
let count = 8

// create array of appropriate length:
var array = [UInt8](count: count, repeatedValue: 0)

// copy bytes into array
fileData.getBytes(&array, length:count * sizeof(UInt8))

var st = String(NSString(format:"%02X %02X %02X %02X %02X %02X %02X %02X",
array[0], array[1], array[2], array[3], array[4], array[5], array[6], array[7]))

// 49 44 33 is mp3

//
print("first \(count) bytes are \(st)")

// f t y p seems to determine a .mp4 file
st = String(NSString(format:"%c %c %c %c %c %c %c %c",
array[0], array[1], array[2], array[3], array[4], array[5], array[6], array[7]))

print("first \(count) bytes are \(st)")
}
} catch let error as NSError {
print("error while trying to read from \(pathToFile) - \(error.localizedDescription)")
}


Related Topics



Leave a reply



Submit