UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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?

2      

Are you using iOS simulator or physical device?

2      

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

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.

2      

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?

2      

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.

3      

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?

2      

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

2      

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.

2      

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.

2      

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

2      

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?

2      

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.

2      

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

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.