我需要时间持续时间和结束事件的midi文件。我正在使用下面的代码播放midi文件。我试过了,但什么也没找到。提前谢谢
var s: MusicSequence?
NewMusicSequence(&s)
let midiFilePath = Bundle.main.path(forResource: "CCL-20180308-A-04", ofType: "mid")
let midiFileURL = URL(fileURLWithPath: midiFilePath ?? "")
MusicSequenceFileLoad(s!, midiFileURL as CFURL, MusicSequenceFileTypeID(rawValue: 0)!, [])
var p: MusicPlayer?
NewMusicPlayer(&p)
MusicPlayerSetSequence(p!, s)
MusicPlayerPreroll(p!)
MusicPlayerStart(p!)
usleep(3 * 100 * 100)
var now: MusicTimeStamp = 0
MusicPlayerGetTime(p!, &now)
最佳答案
这将起作用:
var s: MusicSequence!
NewMusicSequence(&s)
let midiFileURL = Bundle.main.url(forResource: "CCL-20180308-A-04", withExtension: "mid")!
MusicSequenceFileLoad(s!, midiFileURL as CFURL, .midiType, [])
var p: MusicPlayer!
NewMusicPlayer(&p)
MusicPlayerSetSequence(p, s)
MusicPlayerPreroll(p)
MusicPlayerStart(p)
var numTracks: UInt32 = 0
MusicSequenceGetTrackCount(s, &numTracks)
let length = (0..<numTracks).map { (index: UInt32) -> (MusicTimeStamp) in
var track: MusicTrack?
MusicSequenceGetIndTrack(s, index, &track)
var size = UInt32(MemoryLayout<MusicTimeStamp>.size)
var scratchLength = MusicTimeStamp(0)
MusicTrackGetProperty(track!, kSequenceTrackProperty_TrackLength, &scratchLength, &size)
return scratchLength
}.max() ?? 0
var lengthInSeconds = Float64(0)
MusicSequenceGetSecondsForBeats(s, length, &lengthInSeconds)
self.timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { (t) in
var now: MusicTimeStamp = 0
MusicPlayerGetTime(p, &now)
var nowInSeconds = Float64(0)
MusicSequenceGetSecondsForBeats(s, now, &nowInSeconds)
print("\(nowInSeconds) / \(lengthInSeconds)")
})
你遗漏的一个重要部分是通过找到最长轨迹的长度来得到序列的总长度。对于
MusicTrackGetProperty()
属性,可以使用kSequenceTrackProperty_TrackLength
获取轨迹的长度。就其价值而言,CoreMIDI已经足够强大了,特别是在Swift中,我认为使用更高级别的API是值得的。查看
AVMIDIPlayer
,它是AVFoundation的一部分。如果您需要更复杂的东西,可以查看MIKMIDI,这是一个开源的MIDI库,它构建在核心MIDI之上,但是增加了大量额外的功能,而且使用起来非常容易。(免责声明:我是MIKMIDI的原始作者和维护者)对于MIKMIDI,您可以这样做:let midiFileURL = Bundle.main.url(forResource: "CCL-20180308-A-04", withExtension: "mid")!
let sequence = try! MIKMIDISequence(fileAt: midiFileURL)
let sequencer = MIKMIDISequencer(sequence: sequence)
sequencer.startPlayback()
self.timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { (t) in
let now = sequencer.timeInSeconds(forMusicTimeStamp: sequencer.currentTimeStamp, options: [])
let length = sequence.durationInSeconds
print("\(now) / \(length)")
})
简单一点!如果你想录音,更复杂的合成,将MIDI路由到外部设备,等等,事情会变得更有趣。
关于ios - 如何从iOS中的Music Player中获取持续时间(对于Midi文件)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57070161/