В моем проекте очень хорошо воспроизводятся все звуки, необходимые для таймера медитации. Теперь я хочу, чтобы пользователи могли выбирать музыку из хранилища своего iPhone, чтобы затем воспроизводить ее во время работы таймера.
Я создал таймер, просто используя музыкальный файл, который я перетащил в свой проект. и все, как всегда, работает нормально.
Затем я попробовал поместить URL-адрес из файла хранилища, который выбрал пользователь. Но ничего не играет. Таймер работает без проблем и ошибок не возникает. Можно ли вообще использовать AVAudioPlayer для воспроизведения мультимедиа, внешнего по отношению к проекту? Я видел несколько примеров, когда люди использовали его для воспроизведения мультимедиа с URL-адреса в Интернете. Я решил, что это должно сработать.
Вот необходимые фрагменты кода, а также снимок экрана с URL-адресом файла, который выбран и затем сохранен пользователем.
import SwiftUI
import SwiftData
import AVFoundation /// For playing any sound
import AVKit /// For the AirPlay Button
import MediaPlayer /// For getting the Volume Slider attached to the devices volume.
import CoreHaptics /// For making vibrations once the timer is run out
struct TimerTapasMusicView: View {
@Environment(\.dismiss) var dismiss /// To be able to dismiss the view
@State var countdownTimer = 5 * 60 /// The actual seconds of the timer, being counted down/up
@State var timerRunning = true /// Var to set and see if timer is running
@State var gongSound: AVAudioPlayer? /// The Sound of the timer
**@State var musicSound: AVAudioPlayer? /// The Sound of the music**
@State private var hours: Int = 0 /// Vars for the picker wheel
@State private var minutes: Int = 0
@State private var seconds: Int = 0
@State private var brightnessLow = false/// Var for saving if the brightness button was used
@State private var engine: CHHapticEngine? /// The object creating the vibrations later on
@Environment(\.scenePhase) var scenePhase /// Var to keep track of state of app, to restart HapticEngine
/// Environment Objects
@EnvironmentObject var userStat: StatisticsObject /// Var to keep track of seconds using the Timer
@EnvironmentObject var envObject: EnvObject /// For getting FullDarkness, vibrateTimer
/// Getting the Asana
@State var asana: TapasAsana
**let path = Bundle.main.path(forResource: "bell_basu.mp3", ofType:nil)!
let musicPath = Bundle.main.path(forResource: "authen.mp3", ofType:nil)!
let volumeView = MPVolumeView()**
var body: some View {
/// For calculating hours, minutes, seconds
let style = Duration.TimeFormatStyle(pattern: .minuteSecond)
//let formTimer = Duration.seconds(countdownTimer).formatted()
let formTimerShort = Duration.seconds(countdownTimer).formatted(style)
**let url = URL(fileURLWithPath: path)
let musicUrl = asana.musicFile //URL(fileURLWithPath: musicPath)**
VStack {
/// The slider for the system volume
HStack{
VolumeSliderView()
.frame(width: 250, height: 25)
.offset(y: 5)
RouteButtonView()
.frame(width: 50, height: 50)
}
.padding(.top, 40)
/// The buttons when the timer is running
TimerTopButtonsView()
Text("\(asana.name)")
.font(.system(size: 50))
.padding(.bottom, -100)
/// The main Timer If there are no hours we hide the hour number and make the timer bigger in this way.
Text("\(formTimerShort)")
.onAppear(perform: prepareHaptics) /// Preparing the Vibration Object
.onChange(of: scenePhase) { /// When app gets closed and reopnened, start Haptic again
prepareHaptics()
}
.onReceive(Timer.publish(every: 1, on: .main, in: .common).autoconnect()) { _ in
if countdownTimer > 0 && timerRunning {
countdownTimer -= 1
}
else if countdownTimer == 5 {
gongSound?.prepareToPlay()
} else {
timerRunning = false
}
/// Plays the gong sound when timer hits 0 after running
if countdownTimer == 0 && timerRunning {
do {
gongSound = try AVAudioPlayer(contentsOf: url)
gongSound?.play()
envObject.fullDarkness = false
timerRunning = false
timerVibration()
/// Adding the seconds of lastTime to the TimerUsed stat
userStat.timerDuration += asana.duration
UserDefaults.standard.set(userStat.timerDuration, forKey: "TimerDuration")
/// When the Timer is finished we have done the Asana and the Timer is dismissed.
asana.doneToday = true
asana.recoupCount = 0
} catch {
//Couldn't Load File.
}
}
}
.frame(width: 500, height: 220)
/// Change the size depending if it is only minutes and then only when timer running
.font(.system(size: 140))
.monospacedDigit() /// Makes the numbers fixed in size and position.
.onTapGesture { gongSound?.stop() } /// Tapping it stops the sound.
.padding(.top, 30)
.padding(.bottom, 30)
/// Prevents device from sleep on appear and allows sleep on disappear
.onAppear{
UIApplication.shared.isIdleTimerDisabled = true
if (asana.recoupCount == 0 ) { countdownTimer = asana.duration }
else { countdownTimer = asana.duration * (asana.recoupCount + 1) }
**do {
musicSound = try AVAudioPlayer(contentsOf: musicUrl)
musicSound?.play()
musicSound?.numberOfLoops = 10000**
} catch {
}
}
.onDisappear{UIApplication.shared.isIdleTimerDisabled = false}
.toolbar(.hidden, for: .tabBar)
.... And more Code that I think is not important here.
Здесь я разрешаю пользователю выбрать файл из своего хранилища:
} else if asana.executionType == "music" {
Button("Choose Music File") {
chooseMusic = true
}
.fileImporter(isPresented: $chooseMusic, allowedContentTypes: [.item]) {result in
switch result {
case .success(let Fileurl):
print(Fileurl)
asana.musicFile = Fileurl
case .failure(let error):
print(error)
}
}
Text("File Name: \(asana.musicFile)")
Это снимок экрана URL-адреса, возможно, я сохраняю его неправильно.
Я отредактировал код, включив в него область безопасности. согласно примеру в документации, но звука все равно нет.
.fileImporter(isPresented: $chooseMusic, allowedContentTypes: [.item]) {result in
switch result {
case .success(let Fileurl):
let gotAccess = Fileurl.startAccessingSecurityScopedResource()
print(Fileurl)
asana.musicFile = Fileurl
Fileurl.stopAccessingSecurityScopedResource()
case .failure(let error):
print(error)
}
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... om-storage
Как использовать AVAudioPlayer для воспроизведения музыкальных файлов из хранилища? ⇐ IOS
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Синхронизируйте скорость воспроизведения AVAudioPlayer и AVAudioSequencer
Anonymous » » в форуме IOS - 0 Ответы
- 5 Просмотры
-
Последнее сообщение Anonymous
-