[英]How to differentiate a MP3,MP4 file?
我不想使用 pathExtension 来执行此操作,因为它不严格。 我通过文件头区分图像文件,但我找不到关于 MP3/MP4 的任何信息。
(Swift或者OC都可以)
要确定它是 mp3,请查看文件的前两个或三个字节。 如果它是49 44 33
或ff fb
,你有一个 mp3 。
这是我为此目的编写的一些 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)")
}
你会想做你对图像所做的事情,并使用两个文件中的标题信息来确定它是 mp3 文件还是 mp4 文件。 这里有关于 mp4 标头的信息: 任何熟悉 mp4 数据结构的人? .
斯威夫特 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)")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.