在Swift Playground中播放音符

时间:2016-05-08 17:24:42

标签: ios swift audio swift-playground audiotoolbox

我正在尝试在Swift Playground中播放默认正弦波作为声音的短音符序列。稍后我会用 Soundfont 替换声音,但此刻我会对产生一些声音感到满意。

我希望这是一个像midi一样的序列,可以直接控制音符,而不是纯粹基于音频的。 AudioToolbox似乎提供了我正在寻找的东西,但我很难完全理解它的用法。这是我目前正在尝试的事情

import AudioToolbox

// Creating the sequence    

var sequence:MusicSequence = nil
var musicSequence = NewMusicSequence(&sequence)

// Creating a track

var track:MusicTrack = nil
var musicTrack = MusicSequenceNewTrack(sequence, &track)

// Adding notes

var time = MusicTimeStamp(1.0)
for index:UInt8 in 60...72 {
    var note = MIDINoteMessage(channel: 0,
                               note: index,
                               velocity: 64,
                               releaseVelocity: 0,
                               duration: 1.0 )
    musicTrack = MusicTrackNewMIDINoteEvent(track, time, &note)
    time += 1
}

// Creating a player    

var musicPlayer:MusicPlayer = nil
var player = NewMusicPlayer(&musicPlayer)

player = MusicPlayerSetSequence(musicPlayer, sequence)
player = MusicPlayerStart(musicPlayer)

你可以想象,没有声音播放。我很欣赏有关如何大声播放声音序列的任何想法。

2 个答案:

答案 0 :(得分:14)

您必须为Playground启用异步模式。

在顶部添加它(Xcode 7,Swift 2):

import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

你的序列将会播放。

Xcode 8(Swift 3)也一样:

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

答案 1 :(得分:0)

在Swift Playground中工作的MIDI示例

import PlaygroundSupport
import AudioToolbox

var sequence : MusicSequence? = nil
var musicSequence = NewMusicSequence(&sequence)

var track : MusicTrack? = nil
var musicTrack = MusicSequenceNewTrack(sequence!, &track)

// Adding notes

var time = MusicTimeStamp(1.0)
for index:UInt8 in 60...72 { // C4 to C5
    var note = MIDINoteMessage(channel: 0,
                               note: index,
                               velocity: 64,
                               releaseVelocity: 0,
                               duration: 1.0 )
    musicTrack = MusicTrackNewMIDINoteEvent(track!, time, &note)
    time += 1
}

// Creating a player

var musicPlayer : MusicPlayer? = nil
var player = NewMusicPlayer(&musicPlayer)

player = MusicPlayerSetSequence(musicPlayer!, sequence)
player = MusicPlayerStart(musicPlayer!)

PlaygroundPage.current.needsIndefiniteExecution = true

MIDI reference page很棒,图表很好

MIDI Notes Reference