按下按钮时如何播放/暂停声音

问题描述 投票:0回答:1

当我按下按钮时,我需要播放声音(在资产中)。我收到错误:“找不到音频文件” 我上了这门课:

import SwiftUI
import AVFoundation

class AudioPlayerViewModel: ObservableObject {
  var audioPlayer: AVAudioPlayer?

  @Published var isPlaying = false

  init() {
      if let sound = Bundle.main.path(forResource: "thesound", ofType: "mp3") {
      do {
        self.audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound))
      } catch {
        print("AVAudioPlayer could not be instantiated.")
      }
    } else {
      print("Audio file could not be found.")
    }
  }

  func playOrPause() {
    guard let player = audioPlayer else { return }

    if player.isPlaying {
      player.pause()
      isPlaying = false
    } else {
      player.play()
      isPlaying = true
    }
  }
    
    
}

我在 ContentView 中得到了这个按钮:

Button(action: {
            audioPlayerViewModel.playOrPause()
          }) {
            Image(audioPlayerViewModel.isPlaying ? "pause" : "play")
              .resizable()
              .scaledToFit()
              .frame(width: 80, height: 80)
              .foregroundColor(.white)

谢谢!

我尝试将

 inDirectory: "Assets"
添加到
 if let sound = Bundle.main.path(forResource: "thesound", ofType: "mp3", inDirectory: "Assets")
中,但没有帮助

swiftui avaudioplayer playsound
1个回答
0
投票

试试这个:

if let sound = Bundle.main.url(forResource: "thesound", withExtension: "mp3")

© www.soinside.com 2019 - 2024. All rights reserved.