在Swift Playground中播放音符

时间:2023-01-23 22:53:00

I am trying to play a short musical note sequence with a default sine wave as sound inside a Swift Playground. At a later point I'd like to replace the sound with a Soundfont but at the moment I'd be happy with just producing some sound.

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

I want this to be a midi like sequence with direct control over the notes, not something purely audio based. The AudioToolbox seems to provide what I am looking for but I have troubles fully understanding its usage. Here's what I am currently trying

我希望这是一个像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)

As you can imagine, there's no sound playing. I appreciate any ideas on how to have that sound sequence playing aloud.

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

1 个解决方案

#1


12  

You have to enable the asynchronous mode for the Playground.

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

Add this at the top (Xcode 7, Swift 2):

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

import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

and your sequence will play.

你的序列将会播放。

The same for Xcode 8 (Swift 3):

Xcode 8(Swift 3)也是如此:

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

#1


12  

You have to enable the asynchronous mode for the Playground.

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

Add this at the top (Xcode 7, Swift 2):

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

import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

and your sequence will play.

你的序列将会播放。

The same for Xcode 8 (Swift 3):

Xcode 8(Swift 3)也是如此:

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true