如何区分MP3,MP4文件?

时间:2016-01-20 10:46:32

标签: ios objective-c swift

我不想使用pathExtension来执行此操作,因为它并不严谨。我通过文件标题区分了图像文件,但我无法找到有关MP3 / MP4的任何信息。

(Swift或OC都可以)

3 个答案:

答案 0 :(得分:4)

要确定它是一个mp3,请查看该文件的前两个或三个字节。 If it's 49 44 33 or ff fb, you have a mp3

And a signature of ftyp may indicate a .mp4 file

这是我为此目的而编写的一些Swift代码:

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)")
}

答案 1 :(得分:1)

您想要对图像执行的操作,并使用两个文件中的标题信息来确定它是mp3文件还是mp4文件。这里有关于mp4标题的信息:Anyone familiar with mp4 data structure?

答案 2 :(得分:0)

快捷键5

func doStuff(fileData: Data) {
    if fileData.count > 0 {
        let count = 8

        // create array of appropriate length:
        var array = [UInt8](unsafeUninitializedCapacity: count) { buffer, initializedCount in
            for x in 0..<count { buffer[x] = 0 }
            initializedCount = count
        }

        // copy bytes into array
        fileData.copyBytes(to: &array, count: count * UInt8.bitWidth)

        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)")
    }
}