Download music file from server and save in my app(从服务器下载音乐文件并保存在我的应用程序中)
问题描述
我需要从服务器下载一个 .mp3 音频文件以保存在我的应用程序中,无需下载即可播放,就像下面的屏幕截图一样,带有下载进度条(我在 App Store 中找到了这个).任何人都可以通过源代码帮助我在我的应用程序中执行此操作吗?任何帮助将不胜感激!提前致谢!
I need to download an .mp3 audio file from a server to save in my app and play it without downloading, exactly like the screenshot below, with a progress bar for the download (I found this in the App Store). Can anyone help me to do this in my app, with source code? Any help will be appreciated! Thanks in advance!
我使用了 NSURLConnection,但它对我不起作用.
I used NSURLConnection but it does not really work for me.
这是我正在尝试做的屏幕截图.
Here is the screenshot of what I am trying to do.
推荐答案
这个问题讨论了你在寻找什么
This questions discusses what you're looking for
如果你想下载一个文件然后播放它,你需要做的是:
If you want to download a file THEN play it, what you need to do is:
使用 NSURLConnection 将文件下载到磁盘 - this 链接讨论了保存大文件(当我不需要它们时,我不会在内存中保留 2-5mb,即使我认为它会可能工作).
use an NSURLConnection to download the file to the disk - this link discusses saving large files (i wouldn't keep 2-5mb's in the memory when i don't need them even thought it will probably work).
,比 AVAudioPlayer 播放它 - 检查 this 出去.
, than an AVAudioPlayer to play it - check this out.
编辑 2:
对于取消按钮,它实际上应该只调用 [NSURLConnection cancel] 方法并执行完成下载类所需的任何其他操作...
For the cancel button, it should practically just call the [NSURLConnection cancel] method and do whatever other finishing up your download class is gonna need...
对于进度条,在 NSURLConnectionDelegate 方法 didReceiveResponse 中,您获取 NSURLResponse,将其转换为 NSHTTPURLResponse,并使用 expectedContentLength 方法.
For the progress bar, in the NSURLConnectionDelegate method didReceiveResponse, you take the NSURLResponse, cast it to a NSHTTPURLResponse, and retrieve the size of the file you're downloading using the expectedContentLength method.
然后在每次调用 NSURLConnection:didRecieveData 方法时,使用 [数据长度] 方法计算传入字节数,然后除以 expectedContentLength 来自上一个 URL响应,这是代表您传递给进度视图的进度的浮点数 progress 属性
And then in each call to the NSURLConnection:didRecieveData method you count the incoming bytes using [data length] method, divide it by the expectedContentLength from the previous URL response and that's the float the represents your progress that you pass to the progress view's progress property
这篇关于从服务器下载音乐文件并保存在我的应用程序中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从服务器下载音乐文件并保存在我的应用程序中
基础教程推荐
- iOS4 创建后台定时器 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
