Tho*_*mas 6 midi casting objective-c coremidi swift
我正在看一些使用核心midi的midi输出的例子.
特别是 这个问题
而且这个
我在objC中有基于这些的代码,我现在想尝试将其转换为swift.
我最不了解的是这一行: MIDIPacketList* pktList = (MIDIPacketList*) pktBuffer;
我读这个是声明一个MIDIPacketList类型的指针pktlist,并为它赋值pktBuffer,强制转换为类型MIDIPacketList
我是C和objC的新手,这对我来说毫无意义.
MIDIPacketList是这里定义的结构:
以什么方式将bytearray强制转换为结构类型MIDIPacketList,这是什么意思?我想这是试图定义数据包列表的大小,但为什么我们需要在这里做到这一点,无论如何这样做呢?为什么用MIDIPacketListAdd来做这件事就好了几行呢?
这是我在swift的midi输出课程的尝试 - 谁能看到出错的地方?在运行之前,此代码在Xcode中不会出错.我在objC中有一个工作版本,但我无法获得swift中定义的数据包列表的大小.(至少我认为这是问题)
import Foundation
import CoreMIDI
class MidiOutClass {
var midiClient = MIDIClientRef()
var midiSource = MIDIEndpointRef()
func openOutput() {
MIDIClientCreate("MIDI client", nil, nil, &midiClient)
MIDISourceCreate(midiClient, "MIDI Source",&midiSource)
println("midi out opened")//should only do this if successful
}
func noteOn(channel: Int, note: Int, velocity:Int) {
midisend((0x90+channel), note: note, value: velocity)
}
func polyAfter(channel: Int, note: Int, value:Int) {
midisend((0xA0+channel), note: note, value: value)
}
func noteOff(channel: Int, note: Int) {
midisend((0x90+channel), note: note, value: 0 )
}
func midisend(status:Int, note: Int, value:Int) {
var packet: UnsafeMutablePointer<MIDIPacket> = nil
//var buffer = [Byte](count:1024, repeatedValue: 0)
//this is the array I'm trying to use in a similar way to the obj C.
var packetList: UnsafeMutablePointer<MIDIPacketList> = nil
let midiDataToSend:[Byte] = [Byte(status), Byte(note), Byte(value)];
packet = MIDIPacketListInit(packetList);
packet = MIDIPacketListAdd(packetList, 1024, packet, 0, 3, midiDataToSend);
if (packet == nil ) {
println("failed to send the midi.")
} else {
MIDIReceived(midiSource, packetList)
println("sent some stuff")
}
}
}//end MidiOutClass
Run Code Online (Sandbox Code Playgroud)
我在这个问题上找到了答案
objC版本中的字节数组是一个讨厌的黑客,为packetList分配一些内存
这是我修改后的代码,现在可以使用了.
func midisend(status:Int, note: Int, value:Int) {
var packet = UnsafeMutablePointer<MIDIPacket>.alloc(1)
var packetList = UnsafeMutablePointer<MIDIPacketList>.alloc(1)
let midiDataToSend:[Byte] = [Byte(status), Byte(note), Byte(value)];
packet = MIDIPacketListInit(packetList);
packet = MIDIPacketListAdd(packetList, 1024, packet, 0, 3, midiDataToSend);
if (packet == nil ) {
println("failed to send the midi.")
} else {
MIDIReceived(midiSource, packetList)
println("sent some stuff")
}
packet.destroy()
//packet.dealloc(1)
packetList.destroy()
packetList.dealloc(1)
}
Run Code Online (Sandbox Code Playgroud)
然而,注释掉dealloc似乎是不必要的,我还不确定为什么.MIDIReceived会照顾它吗?
如果有人有更好的解决方案 - 可能根本没有使用指针,请发布!
归档时间: |
|
查看次数: |
2441 次 |
最近记录: |