NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

Playing sound

Forums > SwiftUI

I want to play a sound in my SwiftUI app. It works perfectly when I ho through it in xCode but there isn't any sound on the published app or when I build it.

I used this code in ViewController.swift:

import AVFoundation

var audioPlayer: AVAudioPlayer?

func playSound(sound: String, type: String) {
    if let path = Bundle.main.path(forResource: sound, ofType: type) {
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
            audioPlayer?.play()
        } catch {
            print("ERROR")
        }
    }
}

I used this code in the SwiftUI view where I want the sound to play on appear:

struct VividWaves: View {
  import AVFoundation

  var body: some View {

    //my code for this view...

    .onAppear(perform: {
                        playSound(sound: "vividwaves", type: "wav")
                        audioPlayer?.numberOfLoops = 100
                    })
  }
}

Does anyone know what I'm doing wrong here?

   

Are you using iOS simulator or physical device?

   

For the build I used the iOS simulator. I already published the first version on the App Store which means that it also applies to the physical device

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.

Try it for free

Sponsor Hacking with Swift and reach the world's largest Swift community!

I'm doing the exact same thing in my code; except I don't play on an appear event, I play based on a timer ending. I can't see anything wrong -- particularly makes no sense, if you're saying that this is only failing when you deploy to device.

   

TBH I have the same issue. I mean my app doesn't play any sound (neither in iOS simulator nor in iPhone). Basically my code it's very same as yours.

Also function play() returns true, means there are no issues with playing sounds. I tried older app I created which is not based on SwiftUI and It works fine, plays all sounds, the code is very same.

The code I use in my SwiftUI app is:

    var body: some View {
        Text(sound)
            .onTapGesture {
                print("Row tapped")
                guard let audioFile = Bundle.main.path(forResource: "Floating", ofType: "wav") else {
                    return
                }
                do {
                    let soundPlayer: AVAudioPlayer? = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioFile))
                    guard let player = soundPlayer else { return }

                player.play()

                } catch let error {
                    print("Cannot play sound. \(error.localizedDescription)")
                }
            }
    }

Player.play() returns true. As you can see it is inside SwiftUI struct, but moving it to seperate file didn't help.

Any suggestions?

   

i know this sounds(no pun intended) strange but on the device is the volume on mute. As i will not play sounds on it if it is.

   

In my case I always double checked the volume and it wasn't mute. I even added the AVFoundation.framework in the General setting. Now it works on the preview built but not on the newly updated AppStore app. I even tried it with multiple devices but it still doesn't play anything. Does anyone know if I'm missing something here?

   

Try using in you View

@State var audioPlayer: AVAudioPlayer!

This is my func

func playSounds(_ soundFileName : String) {
    if sound == false {             // Have a toggle to mute sound in app
        guard let soundURL = Bundle.main.url(forResource: soundFileName, withExtension: nil) else {
            fatalError("Unable to find \(soundFileName) in bundle")
        }

        do {
            audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
        } catch {
            print(error.localizedDescription)
        }
        audioPlayer.play()
    }
}

and use in

playSounds("Correct.mp3")

This works maybe missing @State var audioPlayer from yours

   

This doesn't seem to work for me. sound is apperently not declared and shows an error. If I just try to add

@State var audioPlayer: AVAudioPlayer!

the .onAppear functionality of my "subview" doesn't work anymore.

   

Hi Katarina

sound is a var in my app therefore will not be declared in your (unless your add it)

I put the code using .onAppear

import AVFoundation
import SwiftUI

struct ContentView: View {
    @State var audioPlayer: AVAudioPlayer!

    var body: some View {
        ZStack {
            Text("my code in this view")
        }
        .onAppear(perform: {
            playSounds("Correct.mp3")
        })
    }

    func playSounds(_ soundFileName : String) {
        guard let soundURL = Bundle.main.url(forResource: soundFileName, withExtension: nil) else {
            fatalError("Unable to find \(soundFileName) in bundle")
        }

        do {
            audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
        } catch {
            print(error.localizedDescription)
        }
        audioPlayer.play()
    }
}

and when appears it plays the sound. Try it with your "vividwaves.wav" instead of "Correct.mp3" and see if that works

You need the func and audioPlayer in same struct and import AVFoundation on that file.

   

Thanks! I tried this now. It works on the simulator. I'm crossing my fingers that it will work on the updated App Store version

   

So the new version is uploaded but it still won't work :( does anyone know if I'm missing a setting that's crucial for app store versions?

   

I would check how the file sound is added to your project. When you select the file in Xcode do you see it being part of the target? I would guess the problem is that the sound is missing in the App Store version.

   

It works now. The problem was silent mode which preveneted sounds from being played. For some reasons the issue went away in the next version without me changing the code for all of the sound views. Don't know why but at least it works now

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.

Try it for free

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.