gpt4 book ai didi

ios - 去另一个 View Controller 后恢复音乐

转载 作者:行者123 更新时间:2023-11-28 08:02:45 26 4
gpt4 key购买 nike

我正在尝试构建一个音乐应用程序。当我留在音乐 View Controller 中时,音乐正在播放。我还设置了音乐背景模式。音乐正在背景模式下播放,但是当我转到另一个 View Controller 时。音乐重新开始。问题是什么?

这是我的尝试

  //this is global variable 

var player : AVPlayer?
var playerItem:AVPlayerItem?

override func viewDidLoad() {
super.viewDidLoad()
musicplayer()
play()
}



func musicplayer(){

do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)

print("AVAudioSession is Active")

} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}


}

这是我的播放器

    func play(){
let musicUrl = totalAlbumList[myIndex].audiofile
if let mm = musicUrl {
var url: URL!
url = URL(string: mm)
playerItem = AVPlayerItem(url: url)
player = AVPlayer(playerItem: playerItem)
player?.volume = 1.0
player?.rate = 1.0
player?.play()

}

最佳答案

如果你想在所有类中播放音乐,只需将你的 AVPlayer 和所有与播放器相关的代码放在单例类中。

只有当应用程序处于后台模式并且您的 UIViewController 正在运行时,后台模式才有用。使用下面的类来播放音乐。

//
// MusicPlayer.swift
// MusicPlayer
//
// Created by Lakhwinder Singh on 11/09/17.
// Copyright © 2017 lakh. All rights reserved.
//

import UIKit
import AVFoundation

class MusicPlayer: NSObject {

//Constant varialbe of class
static let player = MusicPlayer()

//this is global variable
var player : AVPlayer?
var playerItem:AVPlayerItem?

func initPlayer(){
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)

print("AVAudioSession is Active")

} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}
}

func playMusic(_ musicUrl: String?) {
if let mm = musicUrl {
var url: URL!
url = URL(string: mm)
playerItem = AVPlayerItem(url: url)
player = AVPlayer(playerItem: playerItem)
player?.volume = 1.0
player?.rate = 1.0
player?.play()
}
}

}

只需在您的 AppDelegate 中调用以下代码来初始化播放器。

   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
MusicPlayer.player.initPlayer()
return true
}

并在您的类(class)中使用此代码。

MusicPlayer.player.playMusic(totalAlbumList[myIndex].audiofile)

关于ios - 去另一个 View Controller 后恢复音乐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46157538/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com