ios - 如何一次性下载音频?

标签 ios objective-c audio

我在 tableViewController 中有表格单元格。然后我点击手机音频文件下载,我就可以播放了。但随后我返回 tableViewController 并再次单击单元格音频文件下载。如何一次性下载音频?

AudioPlayer.m

#import "AudioPlayer.h"

@implementation AudioPlayer


- (void) song{
if (_index1 == 0) {
NSString *stringURL = @"https://drive.google.com/uc?export=download&id=0B0EJbcHq3ZALWUo0a05LMWNzeDg";
NSURL  *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"music.mp3"];
    [urlData writeToFile:filePath atomically:YES];
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:filePath] error:nil];

    }
}

}

- (void)initPlayer:(NSString*) audioFile fileExtension:NSURL *audioFileLocationURL = [[NSBundle mainBundle] URLForResource:audioFile withExtension:fileExtension];
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];
[self song];
}


- (void)playAudio {
[self.audioPlayer play];
}


- (void)pauseAudio {
[self.audioPlayer pause];
}


- (BOOL)isPlaying {
return [self.audioPlayer isPlaying];
 }


-(NSString*)timeFormat:(float)value{

float minutes = floor(lroundf(value)/60);
float seconds = lroundf(value) - (minutes * 60);

int roundedSeconds = lroundf(seconds);
int roundedMinutes = lroundf(minutes);

NSString *time = [[NSString alloc]
                  initWithFormat:@"%d:%02d",
                  roundedMinutes, roundedSeconds];
return time;
 }

 - (void)setCurrentAudioTime:(float)value {
[self.audioPlayer setCurrentTime:value];
 }


 - (NSTimeInterval)getCurrentAudioTime {
return [self.audioPlayer currentTime];
 }


 - (float)getAudioDuration {
return [self.audioPlayer duration];
 }


 @end

音频播放器.h

  #import <UIKit/UIKit.h>
  #import <AVFoundation/AVFoundation.h>

  @interface AudioPlayer : UIViewController

  @property (nonatomic, retain) AVAudioPlayer *audioPlayer;

 - (void)initPlayer:(NSString*) audioFile fileExtension:(NSString*)fileExtension;
 - (void)playAudio;
 - (void)pauseAudio;
 - (BOOL)isPlaying;
 - (void)setCurrentAudioTime:(float)value;
 - (float)getAudioDuration;
 - (NSString*)timeFormat:(float)value;
 - (NSTimeInterval)getCurrentAudioTime;

ViewController.m

 #import "ViewController.h"

 @interface ViewController ()

 @end

 @implementation ViewController

 - (void)viewDidLoad
 {
[super viewDidLoad];
if (_index == 0) {
    self.audioPlayer = [[AudioPlayer alloc] init];
    [self setupAudioPlayer:@""];
}
}

 - (BOOL)prefersStatusBarHidden
 {
return NO;
 }


 - (void)setupAudioPlayer:(NSString*)fileName
 {

NSString *fileExtension = @"mp3";

[self.audioPlayer initPlayer:fileName fileExtension:fileExtension];
self.currentTimeSlider.maximumValue = [self.audioPlayer getAudioDuration];


self.timeElapsed.text = @"0:00";

self.duration.text = [NSString stringWithFormat:@"-%@",
                      [self.audioPlayer timeFormat:[self.audioPlayer getAudioDuration]]];

 }


 - (IBAction)playAudioPressed:(id)playButton
 {
[self.timer invalidate];
if (!self.isPaused) {
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"audioplayer_pause.png"]
                               forState:UIControlStateNormal];

    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                  target:self
                                                selector:@selector(updateTime:)
                                                userInfo:nil
                                                 repeats:YES];

    [self.audioPlayer playAudio];
    self.isPaused = TRUE;

} else {
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"audioplayer_play.png"]
                               forState:UIControlStateNormal];

    [self.audioPlayer pauseAudio];
    self.isPaused = FALSE;
  }
 }

 - (void)updateTime:(NSTimer *)timer {
if (!self.scrubbing) {
    self.currentTimeSlider.value = [self.audioPlayer getCurrentAudioTime];
}
self.timeElapsed.text = [NSString stringWithFormat:@"%@",
                         [self.audioPlayer timeFormat:[self.audioPlayer getCurrentAudioTime]]];

self.duration.text = [NSString stringWithFormat:@"-%@",
                      [self.audioPlayer timeFormat:[self.audioPlayer getAudioDuration] - [self.audioPlayer getCurrentAudioTime]]];

if (![self.audioPlayer isPlaying]) {
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"audioplayer_play.png"]
                               forState:UIControlStateNormal];
    [self.audioPlayer pauseAudio];
    self.isPaused = FALSE;
 }
 }

 - (IBAction)setCurrentTime:(id)scrubber {
[NSTimer scheduledTimerWithTimeInterval:0.01
                                 target:self
                               selector:@selector(updateTime:)
                               userInfo:nil
                                repeats:NO];

[self.audioPlayer setCurrentAudioTime:self.currentTimeSlider.value];
self.scrubbing = FALSE;
 }


 - (IBAction)userIsScrubbing:(id)sender {
self.scrubbing = TRUE;
 }


 - (void)didReceiveMemoryWarning
 {
[super didReceiveMemoryWarning];
 }

 @end

ViewController.h

#import <UIKit/UIKit.h>
#import "AudioPlayer.h"

@interface ViewController : UIViewController

@property (nonatomic, strong) AudioPlayer *audioPlayer;

@property (weak, nonatomic) IBOutlet UISlider *currentTimeSlider;
@property (weak, nonatomic) IBOutlet UIButton *playButton;
@property (weak, nonatomic) IBOutlet UILabel *duration;
@property (weak, nonatomic) IBOutlet UILabel *timeElapsed;


@property BOOL isPaused;
@property BOOL scrubbing;

@property NSTimer *timer;

@end

最佳答案

您应该检查该文件是否在本地可用-> (void) song:

NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"music.mp3"];

//Check if file is available locally
//if available load file from the device
{
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:filePath] error:nil];
}
//else: 
{
[urlData writeToFile:filePath atomically:YES];
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:         [NSURL URLWithString:filePath] error:nil];

}

关于ios - 如何一次性下载音频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35680511/

相关文章:

iphone - 检测 MathJax 何时在 UIWebView 中完成加载

ios - 对从 NSDictionary 创建的 NSMutableArray 进行排序

android - Android 上有预定义的声音吗?

ios - 如何在 onReceive 定时器关闭 SwiftUI iOS 中导航另一个 View

android - 使用蓝牙/wi-fi direct/BLE api 或任何其他方式将 ios 设备与 android 设备通信

ios - 使用可选的初始化程序扩展 CollectionType

objective-c - 使用窗口关闭按钮完全关闭 OS X 应用程序

objective-c - 将 NSData append 到 Objective C 中的文件

ios - 您如何使用 iPhone AVAudioPlayer 控制播放级别(分贝?)?或者我需要使用不同的 API 吗?

audio - 使用mplayer从音频流中提取冰冷的元数据(连续)