如何在AVPlayerViewController中播放此视频,并更改从我的Watch发送的Watch Connectivity命令触发的音量(使用swift 2.2)。当我点击手表上的开始/停止时,我得不到任何回复。我的控制台或崩溃没有错误。
import UIKit
import AVKit
import AVFoundation
import WatchConnectivity
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, WCSessionDelegate {
var window: UIWindow?
func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
var replyValues = Dictionary<String, AnyObject>()
let viewController = self.window!.rootViewController
as! AVPlayerViewController
var player = AVPlayer()
let url = "https://example.site/sites/default/files/videos/original/video1bunny_0.mp4"
let playerItem = AVPlayerItem( URL:NSURL( string:url )! )
player = AVPlayer(playerItem:playerItem)
player.rate = 1.0;
switch message["command"] as! String {
case "start" :
player.play()
replyValues["status"] = "Playing"
case "stop" :
player.pause()
replyValues["status"] = "Stopped"
case "volume" :
let level = message["level"] as! Float
//player.adjustVolume(level)
replyValues["status"] = "Vol = \(level)"
default:
break
}
replyHandler(replyValues)
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
if (WCSession.isSupported()) {
let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
if session.paired != true {
print("Apple Watch is not paired")
}
if session.watchAppInstalled != true {
print("WatchKit app is not installed")
}
} else {
print("WatchConnectivity is not supported on this device")
}
return true
} }
我正在尝试调整此代码(在我的ViewController.swift中),该代码在音频播放器中成功播放了mp3。 (我已正确设置了手表上的所有IBActions等。)
class ViewController: UIViewController {
var audioSession: AVAudioSession = AVAudioSession.sharedInstance()
var audioPlayer: AVAudioPlayer?
@IBOutlet weak var volumeControl: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
var url: NSURL?
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
url = NSURL.fileURLWithPath(
NSBundle.mainBundle().pathForResource("vivaldi",
ofType: "mp3")!)
} catch {
print("AudioSession error")
}
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url!,
fileTypeHint: nil)
audioPlayer?.prepareToPlay()
audioPlayer?.volume = 0.1
} catch let error as NSError {
print("Error: \(error.description)")
}
}
答案 0 :(得分:2)
在成功播放MP3的第二个示例中,您已为AVPlayer
设置了视图控制器属性,并将新的音频播放器分配给该属性。视图控制器保留音频播放器,即使在viewDidLoad
代码退出后也会播放:
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer?
然而,在您尝试使用的第一个示例中,只要该代码块退出,您就会使用超出范围的局部变量:
func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
var player = AVPlayer()
音频播放器已经发布,不再存在。
您应该保留音频播放器的该实例,就像您在工作示例中所做的那样。