![]() ![]() At the end, your code should look like the following: If it doesn’t work, make sure you didn’t make a typo in the file name or extension. The drum should be playing well after each tap of the button. I changed the text property to “ Drum!” and centered the button vertically and horizontally to not have to worry about any device’s size.įinally, the button can be linked to a in our ViewController.swift file. To make things more interesting, I decided to add a button to the Storyboard. Whereever you want to play the sound, simply call the play method of the AVAudioPlayer object! This is all it takes for a user to delete your app. It’s better to display or print an error rather than having the user experience a crash. Observe that we are using Bundle to find our way inside the app to go find the file named “ drum” which is of type “ mp3“.Īfter this we initialize the player inside a Do Catch block because we need to be safe and be prepared in case one day, the app isn’t able to load or find the audio file. Then in the viewDidLoad method, I’m going to create a new AVAudioPlayer object and initialize it with the path to the sound file like this: In my demo, I’m going to play a sound in the ViewController class so I’m going to create an instance variable in ViewController.swift to hold the AVAudioPlayer object: At the top of the ViewController.swift file, import the framework like this:Ĭreating and initializing the AVAudioPlayer object In the class that you want to play a sound, you’re going to have to import the AVFoundation classes. When you have a sound file, simply drag it into your Xcode project and it’ll add the file as a resource to your project. You can find a short clip on the net or download the source code for this demo to use the sample MP3 that I used. If you click the “+” icon, you’ll get a dialog and you can search for the AVFoundation Framework to add it.įor this demo, we’re going to need a sample mp3 or wav sound file. ![]() In the General tab of your Xcode project properties, the frameworks and libraries section is all the way at the bottom. The first thing we’ll need to do is to add the AVFoundation framework to the project. You’ll see that it’s actually a really simple task to accomplish! In this AVAudioPlayer tutorial, we’re going to go through an example of playing a sound file that you’ve added to your Xcode project. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |