You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
Music/Music/Services/ShazamService.swift

57 lines
1.5 KiB

import Observation
import ShazamKit
@Observable
final class ShazamService {
var isListening = false
var matchedTitle: String?
var matchedArtist: String?
var errorMessage: String?
private let session = SHManagedSession()
private var listeningTask: Task<Void, Never>?
func startListening() {
guard !isListening else {
stopListening()
return
}
matchedTitle = nil
matchedArtist = nil
errorMessage = nil
isListening = true
listeningTask = Task {
let result = await session.result()
guard !Task.isCancelled else { return }
switch result {
case .match(let match):
if let item = match.mediaItems.first {
matchedTitle = item.title
matchedArtist = item.artist
}
case .noMatch:
errorMessage = "No match found. Try again in a quieter environment."
case .error(let error, _):
errorMessage = "Recognition failed: \(error.localizedDescription)"
@unknown default:
break
}
isListening = false
}
}
func stopListening() {
listeningTask?.cancel()
listeningTask = nil
session.cancel()
isListening = false
}
func clearResult() {
matchedTitle = nil
matchedArtist = nil
errorMessage = nil
}
}