我如何在 iOS 应用中选择音乐文件 [关闭]
Posted
技术标签:
【中文标题】我如何在 iOS 应用中选择音乐文件 [关闭]【英文标题】:How could I select music files in iOS app [closed] 【发布时间】:2020-01-16 06:32:22 【问题描述】:我想在我的 ios 应用中导入 iPhone 的音乐文件。
你能给我看看这个的代码吗?
感谢阅读。
【问题讨论】:
【参考方案1】:看看下面的代码是否适合你,
将“NSAppleMusicUsageDescription”添加到您的 Info.plist 以获得隐私权。 确保您的音乐在您的 iPhone 中可用。它在模拟器中不起作用。
import UIKit
import AVFoundation
import MediaPlayer
class ViewController: UIViewController, MPMediaPickerControllerDelegate
var musicPlayer: AVAudioPlayer?
var pickerVC: MPMediaPickerController?
var mediaItems = [MPMediaItem]()
let currentIndex = 0
override func viewDidLoad()
super.viewDidLoad()
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool)
func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection)
mediaItems = mediaItemCollection.items
updatePlayer()
self.dismiss(animated: true, completion: nil)
func updatePlayer()
let item = mediaItems[currentIndex]
if let path: NSURL = item.assetURL as NSURL?
do
musicPlayer = try AVAudioPlayer(contentsOf: path as URL)
musicPlayer?.enableRate = true
musicPlayer?.rate = 1.0
musicPlayer?.numberOfLoops = 0
musicPlayer?.currentTime = 0
catch
musicPlayer = nil
@IBAction func play(_ sender: AnyObject)
//AVMusicPlayer.deviceCurrentTime
musicPlayer?.play()
@IBAction func stop(_ sender: AnyObject)
musicPlayer?.stop()
@IBAction func picker(_ sender: AnyObject)
pickerVC = MPMediaPickerController(mediaTypes: .music)
pickerVC?.allowsPickingMultipleItems = false
pickerVC?.delegate = self
if let controller = pickerVC
present(controller, animated: true, completion: nil)
【讨论】:
感谢您的回复!今天购买苹果开发者帐户后,我将尝试此代码。谢谢!以上是关于我如何在 iOS 应用中选择音乐文件 [关闭]的主要内容,如果未能解决你的问题,请参考以下文章