Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Function to Play a Tone of Certain Frequency in Swift [closed]

Tags:

ios

swift

audio

I'm looking for a simple way to create a function that will play a tone of a certain frequency in Swift. So far, all I've found requires creating a separate class, or something along those lines. Can anyone point me to some code that can play a tone (of a frequency I choose) within a function?

Thanks!

like image 706
Sunay Avatar asked Oct 19 '25 21:10

Sunay


1 Answers

In general, all synthesized audio in iOS is based on callbacks (functions or blocks), and should be done through a class that contains the asynchronous callback functions or blocks to avoid various problems. It might be possible to stuff all the audio session setup, audio player (unit or queue) initialization, and an audio synthesis render callback block into one Swift function (plus some global state), but it would not be concise (more like over a hundred lines of Swift), and the start-up latency might block your calling thread.

If you don't need to synthesize the tone in your app, you could pre-record your tone, include this audio file in your app, and play it with the AVAudioPlayer API.

If you don't need a pure tone, another possibility is to use CoreMidi to play a musical note.

Added: I put some source code for a Swift 3 class that can play a tone of a given frequency and duration in this Gist: https://gist.github.com/hotpaw2/630a466cc830e3d129b9 It's not a single function, but a class that includes callback blocks.

like image 75
hotpaw2 Avatar answered Oct 21 '25 12:10

hotpaw2