ios - 歌曲不会在 slider 拖动 iOS 上快进

标签 ios objective-c iphone audio

我正在实现一个音频播放器。它工作正常,但 slider 拖动不会更新歌曲。这首歌从头开始,而不是快进。

/*
 * Updates the time label display and
 * the current value of the slider
 * while audio is playing
 */
- (void)updateTime:(NSTimer *)timer {
    //to don't update every second. When scrubber is mouseDown the the slider will not set
    NSLog(@"slider = %f",self.currentTimeSlider.value);

        long currentPlaybackTime = [self.audioPlayer getCurrentAudioTime];
   // self.currentTimeSlider.value = currentPlaybackTime / [self.audioPlayer getAudioDuration];
    if ((currentPlaybackTime / [self.audioPlayer getAudioDuration]) > self.currentTimeSlider.value )
   {
        self.currentTimeSlider.value = currentPlaybackTime / [self.audioPlayer getAudioDuration];

    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]]];
    }
    else{
        //self.currentTimeSlider.value = currentPlaybackTime / [self.audioPlayer getAudioDuration];

        NSLog(@"sliderValuessszz = %f",self.currentTimeSlider.value);

        NSLog(@"audio time = %f",[self.audioPlayer getCurrentAudioTime]);



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

        NSLog(@"time elapsed = %d",self.timeElapsed.text);



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

}

- (IBAction)sliderChanged:(id)currentTimeSlider
{
    NSLog(@"sliderValue = %f",self.currentTimeSlider.value);



    NSLog(@"sliderValuesss = %f",self.currentTimeSlider.value);

    //[self.timer invalidate];
    [self.audioPlayer setCurrentAudioTime:self.currentTimeSlider.value];


    [NSTimer scheduledTimerWithTimeInterval:0.01
                                     target:self
                                   selector:@selector(updateTime:)
                                   userInfo:nil
                                    repeats:NO];





    /*if (!self.isPaused){
        [self.audioPlayer stopAudio];
        [self.audioPlayer setCurrentAudioTime:self.currentTimeSlider.value];
        [self.audioPlayer prepareToPlayAudio];
        [self.audioPlayer playAudio];
    }
    else
    {
        [self.audioPlayer setCurrentAudioTime: self.currentTimeSlider.value];
    }
    */

}

在 slider 上拖动歌曲从头开始,计时器标签也显示开始时间。有人可以帮我解决这个问题吗。

谢谢,

最佳答案

你的MyAudioPlayer.h

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

@interface MyAudioPlayer : UIViewController

@property (nonatomic, retain) AVAudioPlayer *audioPlayer;

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

@end

对应的.m文件

@implementation MyAudioPlayer

/*
 * Init the Player with Filename and FileExtension
 */
- (void)initPlayer:(NSString*) audioFile fileExtension:(NSString*)fileExtension
{
    NSURL *audioFileLocationURL = [[NSBundle mainBundle] URLForResource:audioFile withExtension:fileExtension];
    NSError *error;
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];
}

/*
 * Simply fire the play Event
 */
- (void)playAudio {
    [self.audioPlayer play];
}

/*
 * Simply fire the pause Event
 */
- (void)pauseAudio {
    [self.audioPlayer pause];
}

/*
 * Format the float time values like duration
 * to format with minutes and seconds
 */
-(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;
}

/*
 * To set the current Position of the
 * playing audio File
 */
- (void)setCurrentAudioTime:(float)value {
    [self.audioPlayer setCurrentTime:value];
}

/*
 * Get the time where audio is playing right now
 */
- (NSTimeInterval)getCurrentAudioTime {
    return [self.audioPlayer currentTime];
}

/*
 * Get the whole length of the audio file
 */
- (float)getAudioDuration {
    return [self.audioPlayer duration];
}

@end

初始化方法:

 self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];

View Controller 类

 #import "MyAudioPlayer.h"

@interface ViewController : UIViewController

@property (nonatomic, strong) YMCAudioPlayer *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

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.audioPlayer = [[MyAudioPlayer alloc] init];
    [self setupAudioPlayer:@"audiofile"];
}

/*
 * Setup the AudioPlayer with
 * Filename and FileExtension like mp3
 * Loading audioFile and sets the time Labels
 */
- (void)setupAudioPlayer:(NSString*)fileName
{
    //insert Filename & FileExtension
    NSString *fileExtension = @"mp3";

    //init the Player to get file properties to set the time labels
    [self.audioPlayer initPlayer:fileName fileExtension:fileExtension];
    self.currentTimeSlider.maximumValue = [self.audioPlayer getAudioDuration];

    //init the current timedisplay and the labels. if a current time was stored
    //for this player then take it and update the time display
    self.timeElapsed.text = @"0:00";

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

}

/*
 * PlayButton is pressed
 * plays or pauses the audio and sets
 * the play/pause Text of the Button
 */
- (IBAction)playAudioPressed:(id)playButton
{
    [self.timer invalidate];
    //play audio for the first time or if pause was pressed
    if (!self.isPaused) {
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"audioplayer_pause.png"]
                                   forState:UIControlStateNormal];

        //start a timer to update the time label display
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                      target:self
                                                    selector:@selector(updateTime:)
                                                    userInfo:nil
                                                     repeats:YES];

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

    } else {
        //player is paused and Button is pressed again
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"audioplayer_play.png"]
                                   forState:UIControlStateNormal];

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

/*
 * Updates the time label display and
 * the current value of the slider
 * while audio is playing
 */
- (void)updateTime:(NSTimer *)timer {
    //to don't update every second. When scrubber is mouseDown the the slider will not set
    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]]];
}

/*
 * Sets the current value of the slider/scrubber
 * to the audio file when slider/scrubber is used
 */
- (IBAction)setCurrentTime:(id)scrubber {
    //if scrubbing update the timestate, call updateTime faster not to wait a second and dont repeat it
    [NSTimer scheduledTimerWithTimeInterval:0.01
                                     target:self
                                   selector:@selector(updateTime:)
                                   userInfo:nil
                                    repeats:NO];

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

/*
 * Sets if the user is scrubbing right now
 * to avoid slider update while dragging the slider
 */
- (IBAction)userIsScrubbing:(id)sender {
    self.scrubbing = TRUE;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


self.audioPlayer = [[MyAudioPlayer alloc] init];

设置音频播放器

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

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

更新时间

- (void)updateTime:(NSTimer *)timer {
    //to don't update every second. When scrubber is mouseDown the the slider will not set
    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]]];
}

Reference

关于ios - 歌曲不会在 slider 拖动 iOS 上快进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24406503/

相关文章:

ios - Branch.io 未传递通用链接查询参数以使用 $uri_redirect_mode = 2 重定向 url

ios - NSUInteger 枚举属性应该是指针还是只是原语?

ios - 单元测试用例 - Swift 3.2

ios - 带有两种不同颜色文本的 UILabel

iphone - 以编程方式在 App Store 上运行搜索?

ios - 自定义 UITableViewCell 中缺少附件

iphone - 使用 NSURLConnection 进行长轮询

c++ - 简单的碰撞检测

javascript - 使用 iphone dev 将 HTML 字符串转换为普通文本

ios - swift 错误 : Reference to generic type Dictionary requires arguments in <. ..>