I am a total swift beginner and am working on a tutorial project (magic 8 ball) and have been successful at doing the following:
- play a specific sound when the "Ask" button is pressed.
- play a specific sound when for each of the randomly picked images
However now the sound that should play whenever the button is pressed only plays once and from there on i only hear the sounds that are being displayed with each image. Is this because I am "stuck" in the "if - else" loop ? Or do I have to delay the sounds that are being played for each image in the array ?
Thanks so much for your help !
Here is my code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
#IBOutlet weak var magicBall: UIImageView!
var magicBallDisplay = 1
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
magicBall.image = #imageLiteral(resourceName: "theanswerisyes")
}
#IBAction func askButtonPressed(_ sender: UIButton) {
let magicBallArray = [ #imageLiteral(resourceName: "askagainlater"),#imageLiteral(resourceName: "no"),#imageLiteral(resourceName: "theanswerisyes"),#imageLiteral(resourceName: "yes"),#imageLiteral(resourceName: "noidea")]
magicBall.image = magicBallArray.randomElement()
let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "Ask", ofType: "wav")!)
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
}catch {
print("there was some error. The error was \(error)")
}
audioPlayer.play()
if (magicBall.image?.isEqual(UIImage(named: "yes")))! {
let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "yes", ofType: "mp3")!)
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
} catch {
print("there was some error. The error was \(error)")
}
audioPlayer.play()
}
else if (magicBall.image?.isEqual(UIImage(named: "no")))! {
let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "no", ofType: "mp3")!)
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
} catch {
print("there was some error. The error was \(error)")
}
audioPlayer.play()
}
else if (magicBall.image?.isEqual(UIImage(named: "theanswerisyes")))! {
let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "theanswerisyes", ofType: "mp3")!)
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
} catch {
print("there was some error. The error was \(error)")
}
audioPlayer.play()
}
else if (magicBall.image?.isEqual(UIImage(named: "noidea")))! {
let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "noidea", ofType: "mp3")!)
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
} catch {
print("there was some error. The error was \(error)")
}
audioPlayer.play()
}
else if (magicBall.image?.isEqual(UIImage(named: "askagainlater")))! {
let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "askagainlater", ofType: "mp3")!)
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
} catch {
print("there was some error. The error was \(error)")
}
audioPlayer.play()
}
}
}
I make a new project and change your code to this:
import UIKit
import AVFoundation
class ViewController: UIViewController {
#IBOutlet weak var magicBall: UIImageView!
// you never used this
//var magicBallDisplay = 1
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
magicBall.image = #imageLiteral(resourceName: "theanswerisyes")
}
#IBAction func askButtonPressed(_ sender: UIButton) {
// because you have audio file and image with equal name i made array of string
let magicBallArray = [ "yes","no","theanswerisyes","noidea","askagainlater"]
// check if i get not null item
guard let choosedImageName = magicBallArray.randomElement() else {return}
print(choosedImageName)
// set image with random picked name
magicBall.image = UIImage(named: choosedImageName)
// play ask sound
playSound(fileName: "Ask", fileType: "wav")
// play picked image sound after 10 second from now()
// change number to your needed time
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
self.playSound(fileName: choosedImageName, fileType: "mp3")
})
}
private func playSound(fileName: String, fileType: String)
{
// check if you find the audio file
guard let url = Bundle.main.path(forResource: fileName, ofType: fileType) else {
print("path not found")
return
}
// make NSURL from path
let soundURL = NSURL(fileURLWithPath: url)
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
} catch {
print("there was some error. The error was \(error)")
}
audioPlayer.play()
}
}
I explain code for you.
I didn't enable the button. you can improve this code when you came stronger in swift
your code is really messy.
at first, I advise you to make a function for playing sound like that:
func playSound(fileName: String, fileType: String) {
let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: fileName, ofType: fileType)!)
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
}catch {
print("there was some error. The error was \(error)")
}
audioPlayer.play()
}
you must have a callback for first play sound. after finishing the first sound you can check your if-else or you can try switch-case.
also, you can use delay for playing second sound
I'm new to Swift, but I want to change my view controller to play a remote mp3 file in my iOS app. I started with this code to play a song locally, and it works (with functions for the player after):
import AVFoundation
class Music1ViewController: UIViewController {
//5 -
var songPlayer = AVAudioPlayer()
//15 -
var hasBeenPaused = false
//6 -
func prepareSongAndSession() {
do {
//7 - Insert the song from our Bundle into our AVAudioPlayer
songPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "localsong", ofType: "mp3")!))
//8 - Prepare the song to be played
songPlayer.prepareToPlay()
After looking at the AVAudioPlayer documentation, .prepareToPlay() preloads the buffer, which makes me think all I need to do is change the initializer to target a URL.
Then I change the initializer:
songPlayer = try AVAudioPlayer(contentsOf: URL(string: "https://s3.amazonaws.com/kargopolov/kukushka.mp3")!)
I don't get any errors in XCode, but when I run it, I see an error in the console for Thread 1: EXC_BAD_ACCESS (code=1, address=0x48) which makes me think I am approaching this wrong.
Is there a better way to access the remote mp3 file?
Try this code :
You need to add AVKit & AVFoundation to your frameworks path and import them :
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
var player = AVPlayer()
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func localPress(_ sender: Any) {
let path = Bundle.main.resourcePath!+"/sound.mp3"
print(path)
let url = URL(fileURLWithPath: path)
let playerItem = AVPlayerItem(url: url)
player = AVPlayer(playerItem: playerItem)
player.play()
}// i have created a btn for playing a local file, this is it's action
#IBAction func urlPressed(_ sender: Any) {
let playerItem = AVPlayerItem(url: URL(string: "https://yourURL.mp3")!)
player = AVPlayer(playerItem: playerItem)
player.play()
}// i have created another btn for playing a URL file, this is it's action
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
My approach
func preparePlayer() {
guard let url = URL(string: "https://yourURL.mp3") else {
print("Invalid URL")
return
}
do {
let session = AVAudioSession.sharedInstance()
try session.setCategory(AVAudioSessionCategoryPlayback)
let soundData = try Data(contentsOf: url)
audioPlayer = try AVAudioPlayer(data: soundData)
audioPlayer.volume = 1
let minuteString = String(format: "%02d", (Int(audioPlayer.duration) / 60))
let secondString = String(format: "%02d", (Int(audioPlayer.duration) % 60))
print("TOTAL TIMER: \(minuteString):\(secondString)")
} catch {
print(error)
}
}
I have this code in a very simple, single view Swift application in my ViewController:
var audioPlayer = AVAudioPlayer()
#IBAction func playMyFile(sender: AnyObject) {
let fileString = NSBundle.mainBundle().pathForResource("audioFile", ofType: "m4a")
let url = NSURL(fileURLWithPath: fileString)
var error : NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
if (audioPlayer.isEqual(nil)) {
println("There was an error: (er)")
} else {
audioPlayer.play()
NSLog("working")
}
I have added import AVFoundation and audioPlayer is a global variable. When I execute the code, it does print "working", so it makes it through without errors but no sound is played. The device is not in silent.
There's so much wrong with your code that Socratic method breaks down; it will probably be easiest just to throw it out and show you:
var player : AVAudioPlayer! = nil // will be Optional, must supply initializer
#IBAction func playMyFile(sender: AnyObject?) {
let path = NSBundle.mainBundle().pathForResource("audioFile", ofType:"m4a")
let fileURL = NSURL(fileURLWithPath: path)
player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
player.prepareToPlay()
player.delegate = self
player.play()
}
I have not bothered to do any error checking, but the upside is you'll crash if there's a problem.
One final point, which may or may not be relevant: not every m4a file is playable. A highly compressed file, for example, can fail silently (pun intended).
Important that AvPlayer is class member and not in the given function, else it goes out of scope... :)
I had to declare a global player variable
var player: AVAudioPlayer!
and set it in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
player = AVAudioPlayer()
}
Then I could play the audio file wherever like this:
func playAudioFile(){
do {
if audioFileUrl == nil{
return
}
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: audioFileUrl, fileTypeHint: AVFileType.m4a.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
guard let player = player else { return }
player.play()
print("PLAYING::::: \(audioFileUrl)")
}
catch let error {
print(error.localizedDescription)
}
}
}
Here is a working snippet from my swift project. Replace "audiofile" by your file name.
var audioPlayer = AVAudioPlayer()
let audioPath = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("audiofile", ofType: "mp3"))
audioPlayer = AVAudioPlayer(contentsOfURL: audioPath, error: nil)
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
audioPlayer.play()
You can download fully functional Swift Audio Player application source code from here https://github.com/bpolat/Music-Player
for some reason (probably a bug) Xcode can't play certain music files in the .m4a and the .mp3 format I would recommend changing them all to .wav files to get it to play
//top of your class
var audioPlayer = AVAudioPlayer
//where you want to play your sound
let Sound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "sound", ofType: "wav")!)
do {
audioPlayer = try AVAudioPlayer(contentsOf: Sound as URL)
audioPlayer.prepareToPlay()
} catch {
print("Problem in getting File")
}
audioPlayer.play()
var audioPlayer = AVAudioPlayer()
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("KiepRongBuon", ofType: "mp3")!)
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
I used the below code in my app and it works. Hope that is helpful.
var audioPlayer: AVAudioPlayer!
if var filePath = NSBundle.mainBundle().pathForResource("audioFile", ofType:"mp3"){
var filePathUrl = NSURL.fileURLWithPath(filePath)
audioPlayer = AVAudioPlayer(contentsOfURL: filePathUrl, error: nil)
audioPlayer.play()
}else {
println("Path for audio file not found")
}
In Swift Coding using Try catch, this issues will solve and play audio for me and my code below,
var playerVal = AVAudioPlayer()
#IBAction func btnPlayAction(sender: AnyObject) {
let fileURL: NSURL = NSURL(string: url)!
let soundData = NSData(contentsOfURL: fileURL)
do {
playerVal = try AVAudioPlayer(data: soundData!)
}
catch {
print("Something bad happened. Try catching specific errors to narrow things down",error)
}
playerVal.delegate = self
playerVal.prepareToPlay()
playerVal.play()
}
Based on #matt answer but little bit detailed 'cause original answer did not completely satisfied me.
import AVFoundation
class YourController: UIViewController {
private var player : AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
prepareAudioPlayer()
}
#IBAction func playAudio() {
player?.play()
}
}
extension YourController: AVAudioPlayerDelegate {}
private extension YourController {
func prepareAudioPlayer() {
guard let path = Bundle.main.path(forResource: "you-audio", ofType:"mp3") else {
return
}
let fileURL = URL(fileURLWithPath: path)
do {
player = try AVAudioPlayer(contentsOf: fileURL)
} catch let ex {
print(ex.localizedDescription)
}
player?.prepareToPlay()
player?.delegate = self
}
}
swift 3.0:
import UIKit
import AVFoundation
class ViewController: UIViewController
{
var audioplayer = AVAudioPlayer()
#IBAction func Play(_ sender: Any)
{
audioplayer.play()
}
#IBAction func Pause(_ sender: Any)
{
if audioplayer.isPlaying
{
audioplayer.pause()
}
else
{
}
}
#IBAction func Restart(_ sender: Any)
{
if audioplayer.isPlaying
{
audioplayer.currentTime = 0
audioplayer.play()
}
else
{
audioplayer.play()
}
}
override func viewDidLoad()
{
super.viewDidLoad()
do
{
audioplayer = try AVAudioPlayer(contentsOf:URL.init(fileURLWithPath:Bundle.main.path(forResource:"bahubali", ofType: "mp3")!))
audioplayer.prepareToPlay()
var audioSession = AVAudioSession.sharedInstance()
do
{
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
}
catch
{
}
}
catch
{
print (error)
}
}
}
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?
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.
Here's a bit of code I've got added to FlappySwift that works:
import SpriteKit
import AVFoundation
class GameScene: SKScene {
// Grab the path, make sure to add it to your project!
var coinSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "coin", ofType: "wav")!)
var audioPlayer = AVAudioPlayer()
// Initial setup
override func didMoveToView(view: SKView) {
audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)
audioPlayer.prepareToPlay()
}
// Trigger the sound effect when the player grabs the coin
func didBeginContact(contact: SKPhysicsContact!) {
audioPlayer.play()
}
}
Handy Swift extension:
import AudioToolbox
extension SystemSoundID {
static func playFileNamed(fileName: String, withExtenstion fileExtension: String) {
var sound: SystemSoundID = 0
if let soundURL = NSBundle.mainBundle().URLForResource(fileName, withExtension: fileExtension) {
AudioServicesCreateSystemSoundID(soundURL, &sound)
AudioServicesPlaySystemSound(sound)
}
}
}
Then, from anywhere in your app (remember to import AudioToolbox), you can call
SystemSoundID.playFileNamed("sound", withExtenstion: "mp3")
to play "sound.mp3"
This creates a SystemSoundID from a file called Cha-Ching.aiff.
import AudioToolbox
let chaChingSound: SystemSoundID = createChaChingSound()
class CashRegisterViewController: UIViewController {
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
AudioServicesPlaySystemSound(chaChingSound)
}
}
func createChaChingSound() -> SystemSoundID {
var soundID: SystemSoundID = 0
let soundURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), "Cha-Ching", "aiff", nil)
AudioServicesCreateSystemSoundID(soundURL, &soundID)
CFRelease(soundURL)
return soundID
}
With a class & AudioToolbox:
import AudioToolbox
class Sound {
var soundEffect: SystemSoundID = 0
init(name: String, type: String) {
let path = NSBundle.mainBundle().pathForResource(name, ofType: type)!
let pathURL = NSURL(fileURLWithPath: path)
AudioServicesCreateSystemSoundID(pathURL as CFURLRef, &soundEffect)
}
func play() {
AudioServicesPlaySystemSound(soundEffect)
}
}
Usage:
testSound = Sound(name: "test", type: "caf")
testSound.play()
import AVFoundation
var audioPlayer = AVAudioPlayer()
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
let soundURL = NSBundle.mainBundle().URLForResource("04", withExtension: "mp3")
audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil)
audioPlayer.play()
}
}
This code works for me. Use Try and Catch for AVAudioPlayer
import UIKit
import AVFoundation
class ViewController: UIViewController {
//Make sure that sound file is present in your Project.
var CatSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Meow-sounds.mp3", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: CatSound)
audioPlayer.prepareToPlay()
} catch {
print("Problem in getting File")
}
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func button1Action(sender: AnyObject) {
audioPlayer.play()
}
}
var mySound = NSSound(named:"Morse.aiff")
mySound.play()
"Morse.aiff" is a system sound of OSX, but if you just click on "named" within XCode, you'll be able to view (in the QuickHelp pane) where this function is searching the sounds. It can be in your "Supporting files" folder
According to new Swift 2.0 we should use do try catch. The code would look like this:
var badumSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("BadumTss", ofType: "mp3"))
var audioPlayer = AVAudioPlayer()
do {
player = try AVAudioPlayer(contentsOfURL: badumSound)
} catch {
print("No sound found by URL:\(badumSound)")
}
player.prepareToPlay()
this is working with Swift 4 :
if let soundURL = Bundle.main.url(forResource: "note3", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
//Swift 4
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player : AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func notePressed(_ sender: UIButton) {
let path = Bundle.main.path(forResource: "note1", ofType: "wav")!
let url = URL(fileURLWithPath: path)
do {
player = try AVAudioPlayer(contentsOf: url)
player?.play()
} catch {
// error message
}
}
}
Let us see a more updated approach to this question:
Import AudioToolbox
func noteSelector(noteNumber: String) {
if let soundURL = Bundle.main.url(forResource: noteNumber, withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
AudioServicesPlaySystemSound(mySound)
}
import UIKit
import AudioToolbox
class ViewController: UIViewController {
let toneSound : Array = ["note1","note2","note3","note4","note5","note6"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func playSound(theTone : String) {
if let soundURL = Bundle.main.url(forResource: theTone, withExtension: "wav") {
var mySound: SystemSoundID = 0
do {
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
catch {
print(error)
}
}
}
#IBAction func anypressed(_ sender: UIButton) {
playSound(theTone: toneSound[sender.tag-1] )
}
}
You can try this in Swift 5.2
func playSound() {
let soundURL = Bundle.main.url(forResource: selectedSoundFileName, withExtension: "wav")
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
}
catch {
print(error)
}
audioPlayer.play()
}
For Swift 3:
extension SystemSoundID {
static func playFileNamed(_ fileName: String, withExtenstion fileExtension: String) {
var sound: SystemSoundID = 0
if let soundURL = Bundle.main.url(forResource: fileName, withExtension: fileExtension) {
AudioServicesCreateSystemSoundID(soundURL as CFURL, &sound)
AudioServicesPlaySystemSound(sound)
}
}
}
Matt Gibson's solution worked for me, here is the swift 3 version.
if let soundURL = Bundle.main.url(forResource: "ringSound", withExtension: "aiff") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
AudioServicesPlaySystemSound(mySound);
}
Swift 4
import UIKit
import AudioToolbox
class ViewController: UIViewController{
var sounds : [SystemSoundID] = [1, 2, 3, 4, 5, 6, 7]
override func viewDidLoad() {
super.viewDidLoad()
for index in 0...sounds.count-1 {
let fileName : String = "note\(sounds[index])"
if let soundURL = Bundle.main.url(forResource: fileName, withExtension: "wav") {
AudioServicesCreateSystemSoundID(soundURL as CFURL, &sounds[index])
}
}
}
#IBAction func notePressed(_ sender: UIButton) {
switch sender.tag {
case 1:
AudioServicesPlaySystemSound(sounds[0])
case 2:
AudioServicesPlaySystemSound(sounds[1])
case 3:
AudioServicesPlaySystemSound(sounds[2])
case 4:
AudioServicesPlaySystemSound(sounds[3])
case 5:
AudioServicesPlaySystemSound(sounds[4])
case 6:
AudioServicesPlaySystemSound(sounds[5])
default:
AudioServicesPlaySystemSound(sounds[6])
}
}
}
or
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate{
var audioPlayer : AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func notePressed(_ sender: UIButton) {
let soundURL = Bundle.main.url(forResource: "note\(sender.tag)", withExtension: "wav")
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
}
catch {
print(error)
}
audioPlayer.play()
}
}
works in Xcode 9.2
if let soundURL = Bundle.main.url(forResource: "note1", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
Swift code example:
import UIKit
import AudioToolbox
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func notePressed(_ sender: UIButton) {
// Load "mysoundname.wav"
if let soundURL = Bundle.main.url(forResource: "note1", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
}
swift 4 & iOS 12
var audioPlayer: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func notePressed(_ sender: UIButton) {
// noise while pressing button
_ = Bundle.main.path(forResource: "note1", ofType: "wav")
if Bundle.main.path(forResource: "note1", ofType: "wav") != nil {
print("Continue processing")
} else {
print("Error: No file with specified name exists")
}
do {
if let fileURL = Bundle.main.path(forResource: "note1", ofType: "wav") {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileURL))
} else {
print("No file with specified name exists")
}
} catch let error {
print("Can't play the audio file failed with an error \(error.localizedDescription)")
}
audioPlayer?.play() }
}
Use This Function to make sound in Swift (You can use this function where you want to make sound.)
First Add SpriteKit and AVFoundation Framework.
import SpriteKit
import AVFoundation
func playEffectSound(filename: String){
runAction(SKAction.playSoundFileNamed("\(filename)", waitForCompletion: false))
}// use this function to play sound
playEffectSound("Sound File Name With Extension")
// Example :- playEffectSound("BS_SpiderWeb_CollectEgg_SFX.mp3")
This code works for me:
class ViewController: UIViewController {
var audioFilePathURL : NSURL!
var soundSystemServicesId : SystemSoundID = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
audioFilePathURL = NSBundle.mainBundle().URLForResource("MetalBell", withExtension: "wav")
AudioServicesCreateSystemSoundID( audioFilePathURL, &soundSystemServicesId)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func PlayAlertSound(sender: UIButton) {
AudioServicesPlayAlertSound(soundSystemServicesId)
}
}
Swift 3 here's how i do it.
{
import UIKit
import AVFoundation
let url = Bundle.main.url(forResource: "yoursoundname", withExtension: "wav")!
do {
player = try AVAudioPlayer(contentsOf: url); guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error as Error {
print(error)
}
}
Couldn't you just import AVFoundation, select the audio player (var audioPlayer : AVAudioPlayer!), and play the sound? (let soundURL = Bundle.main.url(forResource: "sound", withExtension: "wav")