swift--歌曲播放示例

使用MPMoviePlayerController我们可以是进行音乐播放,如下图:

接口的话,我是自己在本地上搭建了个服务器,自己请求自己

就是用这个神器,获得一个音频文件的地址!

具体代码如下:

//
//  SixteenthViewController.swift
//  SwiftTest
//
//  Created by 伯驹网络 on 2017/10/20.
//  Copyright © 2017年 Nicholas. All rights reserved.
//

import UIKit
import MediaPlayer

class SixteenthViewController: UIViewController,httpTools {
    
    //获取网络数据类
    var hHttp = HttpController()
    //接受频道列表的数组
    var channelData:[AnyObject] = Array()
    
    //隐藏tabbar
    override func viewWillAppear(_ animated: Bool) {
        navigationController?.tabBarController?.tabBar.isHidden = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        navigationController?.tabBarController?.tabBar.isHidden = true
    }
    let imageV = UIImageView()
    let myView = UIView()
    
    //声明一个媒体播放控件
    var audioPlayer = MPMoviePlayerController()
    //声明一个计时器
    var timer:Timer?
    var label:UILabel?
    var progressV:UIProgressView?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        // Do any additional setup after loading the view.
    
      self.creatPlayer()
} func creatPlayer() { progressV = UIProgressView(frame:CGRect(x:20,y:350,width:kScreenWidth-40,height:20)) self.view.addSubview(progressV!) label = UILabel(frame:CGRect(x:40,y:385,width:kScreenWidth-80,height:45)) label?.textColor = UIColor.black self.view.addSubview(label!) self.setOnAudio(url: "http://192.168.0.137:809/Yes,%20I%20Love%20You_Aaron%20Neville_...To%20Make%20Me%20Who%20I%20Am.mp3") } //播放歌曲 func setOnAudio(url:String){ //暂停当前歌曲的播放 self.audioPlayer.stop() //获取歌曲文件 self.audioPlayer.contentURL = URL(string:url) //播放歌曲 self.audioPlayer.play() //先停掉计时器 timer?.invalidate() //将计时器归零 label?.text = "00:00" //开启计时器 timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(onUpdate), userInfo: nil, repeats: true) } func onUpdate() { //返回播放器当前的播放时间 let c = audioPlayer.currentPlaybackTime if c > 0.0 { //歌曲的总时间 let t = audioPlayer.duration print("播放的总时间是:\(t)") //歌曲播放的百分比 let p:CGFloat = CGFloat(c/t) //通过百分比设置进度条 progressV?.setProgress(Float(p), animated: true) //一个小算法,来实现00:00这种格式的播放时间 let all:Int=Int(c) let m:Int=all % 60 let f:Int=Int(all/60) print("时间:\(f)--\(m)") var time:String="" if f<10{ time="0\(f):" }else { time="\(f)" } if m<10{ time+="0\(m)" }else { time+="\(m)" } //更新播放时间 label?.text = time } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }

仅做记录!

客人说

posted @ 2017-10-21 15:32  稻草人11223  阅读(204)  评论(0编辑  收藏  举报
返回顶部