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?
In your . swift file create variable of type AVAudioSession, AVAudioRecorder, AVAudioPlayer to start recording session, recorder instance and to play recorded audio respectively.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With