Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating and playing a sound in swift

So what I want to do is create and play a sound in swift that will play when I press a button, I know how to do it in Objective-C, but does anyone know how to in Swift?

It would be like this for Objective-C:

NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"mysoundname" ofType:@"wav"]]; AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &mySound); 

And then to play it I would do:

AudioServicesPlaySystemSound(Explosion); 

Does anyone know how I could do this?

like image 921
Jacob Banks Avatar asked Jun 04 '14 17:06

Jacob Banks


People also ask

How do I record audio in Swift?

In your . swift file create variable of type AVAudioSession, AVAudioRecorder, AVAudioPlayer to start recording session, recorder instance and to play recorded audio respectively.


1 Answers

This is similar to some other answers, but perhaps a little more "Swifty":

// Load "mysoundname.wav" if let soundURL = Bundle.main.url(forResource: "mysoundname", withExtension: "wav") {     var mySound: SystemSoundID = 0     AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)     // Play     AudioServicesPlaySystemSound(mySound); } 

Note that this is a trivial example reproducing the effect of the code in the question. You'll need to make sure to import AudioToolbox, plus the general pattern for this kind of code would be to load your sounds when your app starts up, saving them in SystemSoundID instance variables somewhere, use them throughout your app, then call AudioServicesDisposeSystemSoundID when you're finished with them.

like image 80
Matt Gibson Avatar answered Sep 22 '22 01:09

Matt Gibson