Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
peterstuart committed Feb 10, 2013
0 parents commit b45f62f
Show file tree
Hide file tree
Showing 4 changed files with 281 additions and 0 deletions.
17 changes: 17 additions & 0 deletions EPSSampler.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//
// EPSSampler.h
//
// Created by Peter Stuart on 02/10/13.
// Copyright (c) 2013 Electric Peel Software. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface EPSSampler : NSObject

- (id)initWithPresetURL:(NSURL *)url;

- (void)startPlayingNote:(UInt32)note withVelocity:(double)velocity;
- (void)stopPlayingNote:(UInt32)note;

@end
222 changes: 222 additions & 0 deletions EPSSampler.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
//
// EPSSampler.m
//
// Created by Peter Stuart on 02/10/13.
// Copyright (c) 2013 Electric Peel Software. All rights reserved.
//

#import "EPSSampler.h"

#import <AssertMacros.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreAudio/CoreAudioTypes.h>

enum
{
kMIDIMessage_NoteOn = 0x9,
kMIDIMessage_NoteOff = 0x8,
};

#define kMidiVelocityMinimum 0
#define kMidiVelocityMaximum 127

@interface EPSSampler ()

@property (readwrite) Float64 graphSampleRate;
@property (readwrite) AUGraph processingGraph;
@property (readwrite) AudioUnit samplerUnit;
@property (readwrite) AudioUnit ioUnit;

- (OSStatus)loadSynthFromPresetURL:(NSURL *)presetURL;
- (BOOL)createAUGraph;
- (void)configureAndStartAudioProcessingGraph:(AUGraph)graph;
- (void)stopAudioProcessingGraph;
- (void)restartAudioProcessingGraph;

@end

@implementation EPSSampler

@synthesize graphSampleRate = _graphSampleRate;
@synthesize samplerUnit = _samplerUnit;
@synthesize ioUnit = _ioUnit;
@synthesize processingGraph = _processingGraph;

#pragma mark - Public Methods

- (id)initWithPresetURL:(NSURL *)url {
self = [super init];
if (self) {
[self createAUGraph];
[self configureAndStartAudioProcessingGraph:self.processingGraph];
[self loadSynthFromPresetURL:url];
}

return self;
}

- (void)startPlayingNote:(UInt32)note withVelocity:(double)velocity {
UInt32 noteNum = note;
UInt32 onVelocity = kMidiVelocityMinimum + (kMidiVelocityMaximum - kMidiVelocityMinimum) * velocity;

UInt32 noteCommand = kMIDIMessage_NoteOn << 4 | 0;

OSStatus result = noErr;
require_noerr(result = MusicDeviceMIDIEvent(self.samplerUnit, noteCommand, noteNum, onVelocity, 0), logTheError);

logTheError:

if (result != noErr)
{
NSLog(@"Unable to start playing the low note. Error code: %d '%.4s'\n", (int)result, (const char *)&result);
}
}

- (void)stopPlayingNote:(UInt32)note
{
UInt32 noteNum = note;
UInt32 noteCommand = kMIDIMessage_NoteOff << 4 | 0;

OSStatus result = noErr;

require_noerr(result = MusicDeviceMIDIEvent(self.samplerUnit, noteCommand, noteNum, 0, 0), logTheError);

logTheError:

if (result != noErr)
{
NSLog(@"Unable to stop playing the low note. Error code: %d '%.4s'\n", (int)result, (const char *)&result);
}
}

#pragma mark - Private Methods

- (BOOL)createAUGraph {
OSStatus result = noErr;
AUNode samplerNode, ioNode;

AudioComponentDescription cd = {};

cd.componentManufacturer = kAudioUnitManufacturer_Apple;
cd.componentFlags = 0;
cd.componentFlagsMask = 0;

result = NewAUGraph(&_processingGraph);
NSCAssert(result == noErr, @"Unable to create an AUGraph object. Error code: %d '%.4s'", (int)result, (const char *)&result);

cd.componentType = kAudioUnitType_MusicDevice;
cd.componentSubType = kAudioUnitSubType_Sampler;

result = AUGraphAddNode(self.processingGraph, &cd, &samplerNode);
NSCAssert(result == noErr, @"Unable to add the Sampler unit to the audio processing graph. Error code: %d '%.4s'", (int)result, (const char *)&result);

cd.componentType = kAudioUnitType_Output;
cd.componentSubType = kAudioUnitSubType_RemoteIO;

result = AUGraphAddNode(self.processingGraph, &cd, &ioNode);
NSCAssert(result == noErr, @"Unable to add the Output unit to the audio processing graph. Error code: %d '%.4s'", (int)result, (const char *)&result);

result = AUGraphOpen(self.processingGraph);
NSCAssert(result == noErr, @"Unable to open the audio processing graph. Error code: %d '%.4s'", (int)result, (const char *)&result);

result = AUGraphConnectNodeInput(self.processingGraph, samplerNode, 0, ioNode, 0);
NSCAssert(result == noErr, @"Unable to interconnect the nodes in the audio processing graph. Error code: %d '%.4s'", (int)result, (const char *)&result);

result = AUGraphNodeInfo(self.processingGraph, samplerNode, 0, &_samplerUnit);
NSCAssert(result == noErr, @"Unable to obtain a reference to the Sampler unit. Error code: %d '%.4s'", (int)result, (const char *)&result);

result = AUGraphNodeInfo(self.processingGraph, ioNode, 0, &_ioUnit);
NSCAssert(result == noErr, @"Unable to obtain a reference to the I/O unit. Error code: %d '%.4s'", (int)result, (const char *)&result);

return YES;
}

- (void)configureAndStartAudioProcessingGraph:(AUGraph)graph {
OSStatus result = noErr;
if (graph)
{
// Initialize the audio processing graph.
result = AUGraphInitialize(graph);
NSAssert(result == noErr, @"Unable to initialze AUGraph object. Error code: %d '%.4s'", (int)result, (const char *)&result);

// Start the graph
result = AUGraphStart(graph);
NSAssert(result == noErr, @"Unable to start audio processing graph. Error code: %d '%.4s'", (int)result, (const char *)&result);

// Print out the graph to the console
CAShow(graph);
}
}

- (OSStatus)loadSynthFromPresetURL:(NSURL *)presetURL {
CFDataRef propertyResourceData = 0;
Boolean status;
SInt32 errorCode = 0;
OSStatus result = noErr;

status = CFURLCreateDataAndPropertiesFromResource(
kCFAllocatorDefault,
(__bridge CFURLRef)presetURL,
&propertyResourceData,
NULL,
NULL,
&errorCode
);

NSAssert(status == YES && propertyResourceData != 0, @"Unable to create data and properties from a preset. Error code: %d '%.4s'", (int)errorCode, (const char *)&errorCode);

CFPropertyListRef presetPropertyList = 0;
CFPropertyListFormat dataFormat = 0;
CFErrorRef errorRef = 0;
presetPropertyList = CFPropertyListCreateWithData(
kCFAllocatorDefault,
propertyResourceData,
kCFPropertyListImmutable,
&dataFormat,
&errorRef
);

if (presetPropertyList != 0) {
result = AudioUnitSetProperty(
self.samplerUnit,
kAudioUnitProperty_ClassInfo,
kAudioUnitScope_Global,
0,
&presetPropertyList,
sizeof(CFPropertyListRef)
);

CFRelease(presetPropertyList);
}

if (errorRef) {
CFRelease(errorRef);
}

CFRelease(propertyResourceData);

return result;
}

- (void)stopAudioProcessingGraph {
OSStatus result = noErr;

if (self.processingGraph) {
result = AUGraphStop(self.processingGraph);
}

NSAssert(result == noErr, @"Unable to stop the audio processing graph. Error code: %d '%.4s'", (int)result, (const char *)&result);
}

- (void)restartAudioProcessingGraph {
OSStatus result = noErr;

if (self.processingGraph) {
result = AUGraphStart(self.processingGraph);
}

NSAssert(result == noErr, @"Unable to restart the audio processing graph. Error code: %d '%.4s'", (int)result, (const char *)&result);
}

@end
9 changes: 9 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Copyright © 2013 Electric Peel, LLC. All Rights Reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY ELECTRIC PEEL, LLC "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# EPSSampler

`EPSSampler` is a wrapper around `AUSampler` functionality, based on Apple’s [Sampler Unit Presets][sample] sample code.

## Requirements

- iOS 5.0 or later

## Setup

1. Add `AudioToolbox`, `AVFoundation`, and `CoreAudio` to your project’s linked libraries.
2. Add `EPSSampler.h` and `EPSSampler.m` to your project.

## Usage

Create an `aupreset` file in AU Lab and add it to your project. (See Session 411 from WWDC 2011 for more details.) Add all the sound files needed by the preset to a folder named `Sounds` in your project. Create an instance of `EPSSampler` with the preset file:

NSURL *presetURL = [[NSBundle mainBundle] URLForResource:@"Preset" withExtension:@"aupreset"];
EPSSampler *sampler = [[EPSSampler alloc] initWithPresetURL:presetURL];

To play and stop notes, use these methods:

`- (void)startPlayingNote:(UInt32)note withVelocity:(double)velocity`
`- (void)stopPlayingNote:(UInt32)note`

The `note` parameters should be the MIDI index of the note you want to start/stop. The `velocity` parameter should be a value between `0` and `1`.

## Notes

AU Lab is no longer included with Xcode. It can be downloaded by choosing Xcode->Open Developer Tools->More Developer Tools… in Xcode, and then choosing Audio Tools for Xcode. There isn’t much document on `AUSampler`—watch Session 411 from WWDC 2011, and read [Technical Note TN2283][tech-note] for more information.

[sample]: https://developer.apple.com/library/ios/samplecode/LoadPresetDemo/Introduction/Intro.html#//apple_ref/doc/uid/DTS40011214
[tech-note]: https://developer.apple.com/library/ios/samplecode/LoadPresetDemo/Introduction/Intro.html#//apple_ref/doc/uid/DTS40011214

0 comments on commit b45f62f

Please sign in to comment.