如何在不下载设备上的mp3文件的情况下从Swift中的URL流式传输音频?我需要导入什么?我需要某些图书馆吗?在info.plist中添加任何内容?请评论您的代码。
答案 0 :(得分:6)
您可以使用iOS AVPLayer从网址流式传输音频。
var player: AVPlayer!
let url = URL.init(string: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3")
let playerItem: AVPlayerItem = AVPlayerItem(url: url!)
player = AVPlayer(playerItem: playerItem)
let playerLayer = AVPlayerLayer(player: player!)
playerLayer?.frame = CGRect(x: 0, y: 0, width: 10, height: 50)
self.view.layer.addSublayer(playerLayer!)
player.play()
答案 1 :(得分:2)
我用您的网址对其进行了测试,并且可以正常工作
var player: AVPlayer?
let url = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
let playerItem = AVPlayerItem( url:NSURL( string:url )! as URL )
player = AVPlayer(playerItem:playerItem)
player!.rate = 1.0;
player!.play()
答案 2 :(得分:0)
对于在线流媒体,您必须使用AVFoundation框架。
var player: AVPlayer!
let url = URL.init(string: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3")
player = AVPlayer.init(url: url!)
玩:
player.play()
暂停:
player.pause()
答案 3 :(得分:0)
可以在这里
import AVFoundation
var progressTimer:Timer?
{
willSet {
progressTimer?.invalidate()
}
}
var playerStream: AVPlayer?
var playerItem: AVPlayerItem?
func playerStream(urlStream : String)
{
if let playerStream = playerStream
{
if playerStream.isPlaying
{
stopProgressTimer()
playerStream.pause()
}
else
{
startProgressTimer()
playerStream.play()
}
}
else
{
if let urlStr = urlStream.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
{
if let TempURL = URL.init(string: urlStr)
{
playerItem = AVPlayerItem(url: TempURL)
playerStream = AVPlayer(playerItem: playerItem)
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidPlayToEndTime), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
}
}
}
}
func playerItemDidPlayToEndTime() {
stopProgressTimer()
self.playProgressView.progress = 0.0
if let playerStream = self.playerStream
{
playerStream.replaceCurrentItem(with: playerItem)
playerStream.seek(to: kCMTimeZero)
// playerStream.seek(to: .zero) swift 4.0
}
}
func stopProgressTimer() {
progressTimer?.invalidate()
progressTimer = nil
}
func startProgressTimer()
{
if #available(iOS 10.0, *) {
progressTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true){_ in
self.updateProgressTimer()
}
}
else {
progressTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.updateProgressTimer), userInfo: nil, repeats: true)
}
}
@objc func updateProgressTimer()
{
if let playerItem = playerItem
{
if let pa = playerStream
{
let floatTime = Float(CMTimeGetSeconds(pa.currentTime()))
let floatTimeDu = Float(CMTimeGetSeconds(playerItem.duration))
playProgressView.progress = Double(floatTime / floatTimeDu)
}
}
}
答案 4 :(得分:0)
$Pattern = @('nature|kite|venue|street|venture')
$Test = (Get-Content -Path .\file.txt | Select-String -Pattern $Pattern -AllMatches)
$Test = foreach {$_.matches.Value}
$t = $Pattern -split('\|')|where{$Test -notcontains $_}
该课程将在后台播放音乐并播放任何音频视频网址。
答案 5 :(得分:0)
fetch(forecast)
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
data.list.forEach(list => {
const iconId = list.weather[0].id;
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const d = new Date(data.list[0].dt * 1000);
const dayName = days[d.getDay()];
console.log(dayName)
// Generate and append html elements on the page
const container = document.querySelector('.container');
const forecastCard = document.createElement('div');
container.appendChild(forecastCard)
forecastCard.classList.add('forecast-card')
const date = document.createElement('h2');
date.textContent = dayName;
forecastCard.appendChild(date);
date.classList.add('date');
const currentTemp = document.createElement('p');
currentTemp.textContent = list.main.temp;
forecastCard.appendChild(currentTemp);
currentTemp.classList.add('current-temp');
const icon = document.createElement('img');
icon.src = `./icons/${list.weather[0].icon}.png`;
forecastCard.appendChild(icon);
icon.classList.add('icon');
const conditions = document.createElement('p');
conditions.textContent = list.weather[0].description;
forecastCard.appendChild(conditions);
conditions.classList.add('conditions');
const humidity = document.createElement('p');
humidity.textContent = `Humidity: ${list.main.humidity}%`;
forecastCard.appendChild(humidity);
humidity.classList.add('humidity');
})
});
应该
func playAudioBackground() {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default, options: [.mixWithOthers, .allowAirPlay])
print("Playback OK")
try AVAudioSession.sharedInstance().setActive(true)
print("Session is Active")
} catch {
print(error)
}
}
因为 .allowAirPlay 不允许与 AVAudioSession.Category.playback 一起使用,并且会导致真实设备抛出异常。它在模拟器上运行良好,但在设备上运行良好,因此您的音频会话将无法正确配置。
我本来会回复的,但我的名声不够高,无法...