Sign in Join
Wiki copytemporary

macOS Audio Recorder: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: macOS Audio Recorder

OldNewLine
1+*(macOS only)*
2+
3+## Supported Audio File and Data Formats
4+
5+## AVAudioRecorder
6+
7+The AVAudioRecorder class is intended to allow you to make audio recordings straight to a file with very little programming overhead. Using audio recorder, you can:
8+
9+- Record until the user stops the recording;
10+- Record for a specified duration;
11+- Pause and resume a recording;
12+- Obtain input audio-level data that you can use to provide level metering.
13+
14+In macOS, the audio comes from the system’s default audio input device as set by a user in System Preferences. To configure a recording, including options such as bit depth, bit rate, and sample rate conversion quality, configure the audio recorder’s settings dictionary.
15+
16+The format in which the AVAudioRecorder will save your file depends on the URL/string you specify for the file you save. Specifically, it depends on the extension of the file name you are saving. If you don't specify any extension or specify one that the AVAudioRecorder does not understand then it will wrap the file in Core Audio Format container. So, see to it that the extension and the AVFormatIDKey match.
17+
18+## Example Code
19+
20+> **Note:** Not every method in the AVAudioRecorder class has been implemented in the code below. Most methods have been implemented. Check the Apple documentation for the rest. The implemented methods are described in detail in the code below. This code has been tested working on a 2018 Mac mini running Mojave with USB microphone.
21+
22+``` pascal
23+//
24+// Note: Free Pascal v3.3.1 (trunk), revision r42644, was used 6-Jan-2019
25+//
26+
27+unit unit1;
28+
29+{$mode objfpc}{$H+}
30+{$modeswitch objectivec1}
31+{$linkframework AVFoundation}
32+
33+interface
34+
35+uses
36+...
37+ MacOSAll,
38+ CocoaAll,
39+ LCLType,
40+...
41+
42+type
43+
44+ { TForm1 }
45+
46+ AVAudioRecorder = objcclass external(NSObject)
47+ public
48+ {Initializes and returns an audio recorder.
49+ url: File system location to record to. File type to record to is inferred
50+ from the file extension included in this parameter’s value.
51+ settings: Settings for the recording session.
52+ outError: Returns, by-reference, a description of the error, if an error
53+ occurs. Pass nil to ignore the error.}
54+ function initWithURL_settings_error (url: NSURL; settings: NSDictionary; outError: NSErrorPtr):id;
55+ message 'initWithURL:settings:error:';
56+
57+ {Calling this method implicitly calls prepareToRecord(), which creates (or
58+ erases) an audio file and prepares the system for recording.}
59+ function avRecord: Boolean; message 'record';
60+
61+ {Creates an audio file at the location specified by the url parameter in the
62+ init() method. If a file already exists at that location, this method
63+ overwrites it. The preparation invoked by this method takes place
64+ automatically when you call record(). Use prepareToRecord when you want
65+ recording to start as quickly as possible upon calling record().}
66+ function prepareToRecord: Boolean; message 'prepareToRecord';
67+
68+ {Pauses a recording. Call record() to resume recording.}
69+ procedure pause; message 'pause';
70+
71+ {Stops recording and closes the audio file.}
72+ procedure stop; message 'stop';
73+
74+ {Deletes a recorded audio file. The audio recorder must be stopped before
75+ you call this method.}
76+ function deleteRecording: Boolean; message 'deleteRecording';
77+
78+ {A Boolean value that indicates whether the audio recorder is recording.}
79+ function isRecording: Boolean; message 'isRecording';
80+
81+ {Audio recorder settings are in effect only after you explicitly call the
82+ prepareToRecord() method, or after you call it implicitly by starting
83+ recording.}
84+ function settings: NSDictionary; message 'settings';
85+
86+ {The time, in seconds, since the beginning of the recording.}
87+ function currentTime: NSTimeInterval; message 'currentTime';
88+
89+ {By default, audio level metering is off for an audio recorder. Because
90+ metering uses computing resources, turn it on only if you intend to use it.}
91+ procedure setMeteringEnabled(newValue: ObjCBOOL); message 'setMeteringEnabled:';
92+
93+ {A Boolean value that indicates whether audio-level metering is enabled.}
94+ function isMeteringEnabled: ObjCBOOL; message 'isMeteringEnabled';
95+
96+ {To obtain current audio power values, you must call this method before you
97+ call averagePower(forChannel:) or peakPower(forChannel:).}
98+ procedure updateMeters; message 'updateMeters';
99+
100+ {The current peak power, in decibels, for the sound being recorded. A return
101+ value of 0 dB indicates full scale, or maximum power; a return value of
102+ -160 dB indicates minimum power (that is, near silence). If the signal
103+ provided to the audio recorder exceeds ±full scale, then the return value
104+ may exceed 0 (ie enter the positive range).}
105+ function peakPowerForChannel (channelNumber: NSUInteger): single; message 'peakPowerForChannel:';
106+
107+ {The current average power, in decibels, for the sound being recorded. A
108+ return value of 0 dB indicates full scale, or maximum power; a return value
109+ of -160 dB indicates minimum power (that is, near silence). If the signal
110+ provided to the audio recorder exceeds ±full scale, then the return value
111+ may exceed 0 (ie, it may enter the positive range).}
112+ function averagePowerForChannel (channelNumber: NSUInteger): single; message 'averagePowerForChannel:';
113+ end;
114+
115+ TForm1 = class(TForm)
116+
117+ ...
118+
119+ private
120+
121+ public
122+
123+ end;
124+
125+var
126+ Form1: TForm1;
127+ MyAudioRecorder : AVAudioRecorder = Nil;
128+
129+implementation
130+
131+{$R *.lfm}
132+
133+...
134+
135+// Convert NSStrings function
136+function NSStringToString(ns: NSString): String;
137+var
138+ pathStr: shortstring;
139+begin
140+ CFStringGetPascalString(CFStringRef(ns),@pathStr,255,CFStringGetSystemEncoding());
141+ Result := pathStr;
142+end;
143+
144+// Record audio to file located in the user's ${TMPDIR}
145+procedure RecordAudio(audioFileName : NSString);
146+var
147+ path : NSString;
148+ url : NSURL;
149+ settings: NSDictionary;
150+ err : NSError;
151+begin
152+ path := NSTemporaryDirectory.stringByAppendingPathComponent(audioFileName);
153+ url := NSURL.fileURLWithPath(path);
154+ settings := Nil;
155+
156+ MyAudioRecorder := AVAudioRecorder.alloc.initWithURL_settings_error(url, settings, @err);
157+
158+ if Assigned(MyAudioRecorder) then
159+ MyAudioRecorder.avrecord
160+ else
161+ NSLog(NSStr('Error in procedure RecordAudio(): %@'), err);
162+end;
163+
164+...
165+
166+// Record audio - format mp4a inferred from filename
167+procedure TForm1.MenuItem27Click(Sender: TObject);
168+begin
169+ RecordAudio(NSStr('testaudio.mp4a'));
170+end;
171+
172+// Pause audio recording
173+procedure TForm1.MenuItem28Click(Sender: TObject);
174+begin
175+ MyAudioRecorder.Pause;
176+end;
177+
178+// Resume audio recording
179+procedure TForm1.MenuItem29Click(Sender: TObject);
180+begin
181+ MyAudioRecorder.avRecord;
182+end;
183+
184+// Stop audio recording and close file
185+procedure TForm1.MenuItem30Click(Sender: TObject);
186+begin
187+ MyAudioRecorder.Stop;
188+end;
189+
190+...
191+
192+finalization
193+
194+If (Assigned (MyAudioRecorder)) then
195+ begin
196+ MyAudioRecorder.Release;
197+ MyAudioRecorder := Nil;
198+ end;
199+
200+end.
201+```
202+
203+## See also
204+
205+- [[macOS Audio Player]]
206+- [[macOS Play Alert Sound]]
207+- [[macOS NSSound]]
208+- [[macOS MIDI Player]]
209+- [[macOS Sound Utilities]]
210+- [[Multimedia Programming]]
211+
212+## External links
213+
214+- [Apple: Working with Audio](https://developer.apple.com/audio/)
215+- [Apple: AVFoundation Framework](https://developer.apple.com/documentation/avfoundation)
216+- [Apple: AVAudioRecorder](https://developer.apple.com/documentation/avfoundation/avaudiorecorder)
217+
218+---
219+*From the Free Pascal wiki, page "macOS Audio Recorder", as it stood on 2020-06-20 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*
220+Category: Audio
221+Category: Code Snippets
222+Category: Multimedia
223+Category: macOS

Back to history