Playing audio is an important part of many apps. One common trick is to fade in the volume of audio playback so we don't surprise or startle the user. This year, Apple has made this much simpler to implement using AVAudioPlayer. Let's take a look.
First we'll set up a standard AVAudioPlayer, and begin playing it at a volume of 0:
Ever since 1983 when Matthew Broderick's IMSAI 8080 began speaking out loud, we've dreamed of computers that can have conversations with us.
In iOS 9, Apple added the ability to synthesize speech using the high-quality 'Alex' voice. Sadly it's only available on US devices for now, but that's sure to change. Let's try it out:
guardletvoice=AVSpeechSynthesisVoice(identifier:AVSpeechSynthesisVoiceIdentifierAlex)else{return}letsynth=AVSpeechSynthesizer()synth.delegate=selfletutter=AVSpeechUtterance(string:"Would you like to play a game?")utter.voice=voicesynth.speakUtterance(utter)
We start by making sure 'Alex' is available, then we make a new synthesizer. Next, we create an AVSpeechUtterance, and set it's voice. Then, we simply tell the synthesizer to speak! Very cool.
Even cooler, we can implement one of the optional functions of AVSpeechSynthesizerDelegate to get live progress callbacks as each word is spoken. Neat!
Sometimes we want to play audio in our apps. It might be a podcast, a song, or a voice memo. Usually, our users will expect this audio to keep playing if they press the home button on their device. Today we'll look at how to get this working. Let's get started:
First let's setup the boilerplate basic audio playback code:
(Making this code "safe" in Swift can get a little ugly. π)
Next, we'll add a function that we'll call before we begin playback that configures our app's shared AVAudioSession to be in the βPlaybackβcategory, and then we'll set the audio session to be active.
We'll first need to request permission from the user to record audio. Once granted, we'll try to set our Audio Session's category to PlayAndRecord, the category Apple suggests for apps that simultaneously record and playback audio.
We'll create a place for our recording to live, then assemble the settings dictionary for our recorder. We instantiate and store our AVAudioRecorder object, then tell it to start recording. Later, we'll call .stop() on it to stop recording. We can also optionally wire up a delegate to get completion callbacks.
Finally, we can play back our file using AVAudioPlayer: